我有一个Angular组件,它订阅了ngOnInit
生命周期挂钩内的Observable。这里还有其他事情在起作用,例如NgRx商店,但这与这个问题无关。因此,相关代码:
...
ngOnInit() {
this.loginForm = this.formBuilder.group({
usernameOrEmail: ['', [Validators.required]],
password: ['', [Validators.required]]
});
this.authenticating$ = this.store.pipe(select(selectUserAuthenticating));
this.authenticating$
.pipe(takeUntil(this.destroy$))
.subscribe(authenticating =>
// This is the relevant part
authenticating ? this.loginForm.disable() : this.loginForm.enable()
);
}
...
现在,我想测试在this.loginForm.disable()
可观察的订阅中是否正在调用this.loginForm.enable()
或authenticating$
。
我已经使用RxJs TestScheduler
和大理石语法对异步Observable进行测试,从而进行了这样的测试:
...
import { TestScheduler } from 'rxjs/testing';
...
describe('LoginComponent', () => {
...
beforeEach(async(() => {
let scheduler: TestScheduler;
...
});
beforeEach(() => {
fixture = TestBed.createComponent(LoginComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
beforeEach(() => {
scheduler = new TestScheduler((actual, expected) => {
expect(actual).toEqual(expected);
});
});
it('should disable the form while the user is authenticating', () => {
const formDisableSpy = jest.spyOn(component.loginForm, 'disable');
scheduler.run(({ hot, expectObservable }) => {
component.authenticating$ = hot('-a', { a: true });
expectObservable(component.authenticating$).toBe('-b', { b: true });
});
component.authenticating$.subscribe(authenticating => {
expect(authenticating).toBe(true);
expect(formDisableSpy).toHaveBeenCalled();
});
});
});
但是,测试结果表明从未调用过函数this.loginForm.disable()
。但是,authenticating
的值已正确测试。查看Jest测试的控制台输出:
Expected mock function to have been called, but it was not called.
expect(authenticating).toBe(false);
> 133 | expect(component.loginForm.enable).toHaveBeenCalled();
| ^
问题
如何在Angular组件的Observable订阅中测试函数调用?