Ric*_*d77 10 karma-jasmine angular
当我运行时ng c my-component,我得到一个包含 2 个 beforeEach 方法的规范文件。
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ MyComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
Run Code Online (Sandbox Code Playgroud)
为什么我有 2 beforeEach,我需要它们吗?所有的教程都只展示了第二个,即非异步的。运行基本测试所需的代码也分为这两种方法。任何原因?
谢谢你的帮助。
小智 7
由于compileComponents()是一个返回承诺的异步函数,所以 beforeEach 被标记为async。所以 Jasmine 知道在进入下一步之前必须解决所有问题(-> 这里是第二个 beforeEach)。第二个 beforeEach 只包含同步代码,所以它没有用async标记。
如果您将所有内容放在一个 beforeEach 中,则可能会发生compileComponents()在调用createComponent(MyComponent)之前不会解析- 这可能会导致错误,但如果compileComponents()足够快,则不会。
规范文件是一个测试套件文件。本质上,其中一个beforeEaches 设置您的测试台,另一个创建组件的实例以进行测试。您确实需要它们来编写测试并让测试实际工作。您正在运行的唯一测试是it块。因此本质上取决于您如何定义测试环境。
| 归档时间: |
|
| 查看次数: |
395 次 |
| 最近记录: |