我有一个组件,它通过服务从服务器加载一些数据,然后显示它。
我为组件编写了以下测试(有效):
...
it('Should contains data after loading', async(() => {
fixture.whenStable().then(() => {
fixture.detectChanges();
expect(element.querySelector('h1').textContent.trim()).toBe(expectedTitle);
expect(element.querySelector('p').textContent.trim()).toBe(expectedParagraph);
element.querySelectorAll('ul > li').forEach((li, index) => {
expect(li.textContent.trim()).toBe(expectedListItem[index]);
});
});
}));
是否有可能将所有预期分成单独的it
测试?
我想有这样的事情:
...
describe('Component contains data after loading', async(() => {
fixture.whenStable().then(() => {
fixture.detectChanges();
it('Should contain title', () => {
expect(element.querySelector('h1').textContent.trim()).toBe(expectedTitle);
});
it('Should contain paragraph', () => {
expect(element.querySelector('p').textContent.trim()).toBe(expectedParagraph);
});
it('Should contain list', () => {
element.querySelectorAll('ul > li').forEach((li, index) => {
expect(li.textContent.trim()).toBe(expectedListItem[index]);
});
});
});
}));
但我在Argument of type '(done: any) => any' is not assignable to parameter of type '() => void'
行中收到错误describe
。
修改
添加了TestBed
设置。
beforeEach(async(() => {
serviceMock = prepareServiceMock();
TestBed.configureTestingModule({
declarations: [
TestComponent
],
providers: [
{ provide: TestService, useValue: serviceMock }
]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TestComponent);
});
答案 0 :(得分:0)
每个测试规范将单独执行。所以你可以做的就是每次在新规范开始时调用fixture.detectChanges();
。
it('Should contain title', async(() => {
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(element.querySelector('h1').textContent.trim()).toBe(expectedTitle);
}
}));
it('Should contain paragraph', async(() => {
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(element.querySelector('p').textContent.trim()).toBe(expectedParagraph);
}
}));
确保每次都创建新的Component。
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
});