如果 anotherObject 是您在上面指定的对象,您可以执行类似的操作。另一个对象 Stackblitz
describe("HelloComponent", () => {
let spectator: Spectator<HelloComponent>;
const createComponent = createComponentFactory({
component: HelloComponent,
providers: [],
detectChanges: false
});
beforeEach(() => {
spectator = createComponent();
});
it("should be disabled", done => {
const errors = [new Error("xyz"), new Error("abc")];
spectator.component.anotherObject = { errorSource$: of(errors) };
spectator.detectChanges();
spectator.component.isSearchEnabled$.subscribe({
next: isSearchEnabled => {
expect(isSearchEnabled).toBeFalse();
//You might want to test here whether your component template/state changed..
done();
}
});
});
it("should be enabled", done => {
spectator.component.anotherObject = { errorSource$: of([]) };
spectator.detectChanges();
spectator.component.isSearchEnabled$.subscribe({
next: isSearchEnabled => {
expect(isSearchEnabled).toBeTrue();
done();
}
});
});
});
如果您从akita 查询中获得 observable,最好的选择是模拟您的 observable 所依赖的查询方法。我没有测试下面的代码,但类似的东西应该可以工作。
let spectator: Spectator<HelloComponent>;
let query: SpyObject<AkitaAnotherObjectQuery>;
const createComponent = createComponentFactory({
component: HelloComponent,
mocks: [AkitaAnotherObjectQuery],
detectChanges: false
});
beforeEach(() => {
spectator = createComponent();
query = spectator.inject(AkitaAnotherObjectQuery);
//return empty array to check if search is enabled by default
query.selectErrorSource.andReturn(of([]));
});
it('should be enabled', () => {
spectator.detectChanges();
//todo test whether component state changed..
});
//test could be fake async or if you want to test the observable you can subscribe to it in the test below
it('should be disabled', () => {
const errors = [new Error('myError')];
query.selectErrorSource.andReturn(of(errors));
spectator.detectChanges();
//todo test whether component state changed..
});
....
希望一切顺利,如果您还有其他问题,请告诉我。如果您愿意,我还可以在 Stackblitz 中添加一个秋田查询模拟示例,请告诉我。