在退出Jasmine测试之前,如何测试Observable是否发布了事件



如果我有这样的场景:

it('some observable', /*done*/() => {

const someService = TestBed.get(SomeService);
const subscription = someService.someObservable.subscribe(value => {
expect(value).toEqual('some value');
subscription.unsubscribe();
/*done();*/
});
// This method is supposed to cause the Observable to publish the value to all subscribers.
someService.setValue('some value');
});

如果Observable从未发布事件,我怎么会失败测试?这个场景有几个问题。首先,如果Observable从不发布事件,则done((方法永远不会被调用。此外,如果它不发布事件,我的测试将如何知道?它看起来不会失败,Jasmine只会打印出测试没有"期望"或类似的内容。

更新:我已经意识到我不需要done((函数,因为我现在在每次测试之前都会重置TestBed。但这仍然不能解决问题,如果Observable没有启动,测试就不会失败。

正如您所提到的,我认为您可以利用done函数。

it('some observable', (done) => { // put done in the callback

const someService = TestBed.get(SomeService);
const subscription = someService.someObservable.subscribe(value => {
expect(value).toEqual('some value');
done(); // call done to let jasmine know that you're done with the test
});
// This method is supposed to cause the Observable to publish the value to all subscribers.
someService.setValue('some value');
});

如果observable没有发布任何事件,则不会调用done,并且测试将挂起async timeout error

以下是我最终的做法:

it('some observable', () => {

const someService = TestBed.get(SomeService);
const someValue = 'some value';
const spy = jasmine.createSpy('someSpy');
const sub = someService.someObservable.subscribe(spy);
someService.setValue(someValue);
expect(spy).toHaveBeenCalledWith(someValue);
sub.unsubscribe();
});

我不知道为什么这样做,因为我认为Observables是异步的。但它似乎可以在不担心异步的情况下工作。也许我只是运气好,这个问题稍后会浮出水面。

最新更新