在 Jasmine 的测试中访问 beforeEach 中定义的常量

Access const defined in beforeEach within test in Jasmine

对于给定的代码,我如何在测试 myTest:

中访问常量 myConst
describe('HeaderCustomerDetailsComponent child components',() => {
  beforeEach(() => {
    ...
    const myConst = "Something";
  });

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

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

定义它

试试这个:

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

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

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

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