如何在beforeAll测试中创建类型变量?

时间:2017-11-09 01:09:36

标签: typescript jasmine mocha jest

我遇到了一个常见的情况。我需要在beforeAll或每个。

中创建一个变量
describe('some test', () => {
  beforeAll(() => {
    const foo = createFoo({}, {});    
  });

  it('returns something', () => {
    // how to access foo?
  });
});

如果我这样做,我无法在foo测试中访问it,因为它只存在于beforeAll范围内。

为了能够访问我需要的地方,我必须在foo内声明describe

describe('', () => {
  let foo;

或使用

this.foo =

这两种方法的问题在于我丢失了类型信息。而且我没有为这类函数的返回类型提供显式接口。

有没有办法在以后可以访问的地方声明foo而不会丢失类型信息?

1 个答案:

答案 0 :(得分:0)

您可以使用non-null assertion operator!)放宽非null约束。

describe('some test', () => {
  let foo!: SomeType;
  beforeAll(() => {
    foo = createFoo({}, {});    
  });

  it('returns something', () => {
    expect(foo.bar).toBe(true);
  });
});
相关问题