【问题标题】:How to create typed variables in beforeAll tests?如何在 beforeAll 测试中创建类型变量?
【发布时间】:2018-04-21 21:14:46
【问题描述】:

我遇到了一个常见的场景。我需要在beforeAll 或每个中创建一个变量。

describe('some test', () => {
  beforeAll(() => {
    const foo = createFoo({}, {});    
  });

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

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

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

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

或者使用

this.foo =

这两种方法的问题是我丢失了类型信息。而且我没有针对这些函数的返回类型的显式接口。

有没有办法在某个地方声明foo,以便我以后可以访问它并且不会丢失类型信息?

【问题讨论】:

    标签: typescript jasmine mocha.js jestjs


    【解决方案1】:

    您可以使用non-null assertion operator (!) 来放松非空约束。

    describe('some test', () => {
      let foo!: SomeType;
      beforeAll(() => {
        foo = createFoo({}, {});    
      });
    
      it('returns something', () => {
        expect(foo.bar).toBe(true);
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-17
      • 1970-01-01
      相关资源
      最近更新 更多