我已经成功地将我的项目转换为使用 Jest 代替 Karma/Jasmine,并且我有很多运行良好的测试。我正在尝试使用 Spectator (^5.2.1) 做一个非常简单的测试,但它不起作用。
我正在尝试测试一个使用 mat-table 呈现表格的库组件。输入是
title:string,
columns: BehaviorSubject<MyColumnDefType> | MyColumnDefType[],
dataSource: MyDataSource | any[]
该组件工作正常,我的所有其他测试工作,直到我尝试使用 setInput 将填充的 mockDataSource 替换为空的。
这是设置:
import {SpectatorHost, createHostFactory} from '@ngneat/spectator/jest';
...OTHER IMPORTS...
describe('MyTableComponent', () => {
let spectator: SpectatorHost<MyTableComponent>;
const createHost = createHostFactory({
component: MyTableComponent,
declarations: [MyTableComponent, MyTableHeaderComponent],
imports: [
BrowserAnimationsModule,
MyMaterialModule,
FlexLayoutModule,
RouterTestingModule
],
mocks: [
MyMaterialModule,
FlexLayoutModule,
BrowserAnimationsModule,
RouterTestingModule
]
});
beforeAll(() => {
Object.defineProperty(window, 'matchMedia', {
value: jest.fn(() => {
return {
matches: true,
addEventListener: jest.fn(),
removeEventListener: jest.fn()
};
})
});
});
const template = `
<my-table
title="TEST TABLE"
[columns]="columns$"
[dataSource]="mockDataSource$">
</my-table>`;
beforeEach( () => {
spectator = createHost(template, {
hostProps: {
columns$: new BehaviorSubject(mockColumns),
mockDataSource$: new MockDataSource(mockData)
}
});
});
...
// THIS TEST PASSES SO CREATEHOST CALL ABOVE WORKS. TABLE CREATED WITH EXPECT # OF CELLS
it ('should all table cells', () => {
expect(
spectator.queryAll('.mat-cell').length
).toEqual(mockData.length * mockColumns.length);
});
...
// THIS IS WHERE IT GOES SOUTH...
it ('should handle empty results', () => {
spectator.setInput('dataSource', new MockDataSource([]));
spectator.setInput('title', 'A NEW TITLE');
spectator.detectChanges();
// THIS TEST WORKS
expect(
spectator.query('.table-title').innerHTML
).toContain('A NEW TITLE');
// THIS TEST FAILS, queryAll STILL RETURNS ORIGINAL VALUE
expect(
spectator.queryAll('.mat-cell').length
).toEqual(0);
出于某种原因,'title' 上的 setInput 有效,但 'dataSource' 上的 setInput 无效(使用 BehaviourSubject 或简单数组输入)。