在Jasmine中测试中的beforeEach中定义的访问const

tim*_*ray 2 unit-testing jasmine karma-runner angular

对于给定的代码,如何myConst在test中访问const myTest

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

  it('myTest', () => {
    expect(myConst).toBeTruthy();
  });
});
Run Code Online (Sandbox Code Playgroud)

Tiz*_*Tiz 5

因为您myConstbeforeEach(...)方法中定义了它的约束范围。最好的方法是移至myConst类级别,并使用进行定义let

尝试这个:

describe('HeaderCustomerDetailsComponent child components',() => {
  let myConst;

  beforeEach(() => {
    ...
    this.myConst = "Something";
  });

  it('myTest', () => {
    expect(this.myConst).toBeTruthy();
  });
});
Run Code Online (Sandbox Code Playgroud)

既然你仍然设定myConstbeforeEach(...)方法你避免测试之间的污染,但你应该还是要小心。