【问题标题】:Access const defined in beforeEach within test in Jasmine在 Jasmine 的测试中访问 beforeEach 中定义的 const
【发布时间】:2017-08-22 16:22:02
【问题描述】:

对于给定的代码,我如何在测试myTest 中访问 c​​onst myConst

describe('HeaderCustomerDetailsComponent child components',() => {
  beforeEach(() => {
    ...
    const myConst = "Something";
  });

  it('myTest', () => {
    expect(myConst).toBeTruthy();
  });
});

【问题讨论】:

    标签: angular unit-testing jasmine karma-runner


    【解决方案1】:

    因为您在 beforeEach(...) 方法中定义了 myConst,所以它被限制在该范围内。最好的方法可能是将myConst 移到类级别,并使用let 定义它。

    试试这个:

    describe('HeaderCustomerDetailsComponent child components',() => {
      let myConst;
    
      beforeEach(() => {
        ...
        this.myConst = "Something";
      });
    
      it('myTest', () => {
        expect(this.myConst).toBeTruthy();
      });
    });
    

    由于您仍在beforeEach(...) 方法中设置myConst,因此您可以避免测试之间的污染,但您仍然应该小心。

    【讨论】:

    • 谢谢!虽然我不得不这样做:const myConst: myConstType = {...someting}; beforeEach(() => { ... // myConst.newProperty = 'maybe'; }); it('myTest', () => { expect(myConst).toBeAwesome(); });
    猜你喜欢
    • 2012-06-26
    • 1970-01-01
    • 1970-01-01
    • 2016-04-16
    • 1970-01-01
    • 2012-05-18
    • 2016-03-07
    • 2020-11-20
    • 1970-01-01
    相关资源
    最近更新 更多