Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ssh/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 在退出Jasmine测试之前,如何测试可观察对象是否发布了事件?_Angular_Jasmine_Observable - Fatal编程技术网

Angular 在退出Jasmine测试之前,如何测试可观察对象是否发布了事件?

Angular 在退出Jasmine测试之前,如何测试可观察对象是否发布了事件?,angular,jasmine,observable,Angular,Jasmine,Observable,如果我有这样一个场景: it('some observable', /*done*/() => { const someService = TestBed.get(SomeService); const subscription = someService.someObservable.subscribe(value => { expect(value).toEqual('some value'); subscription

如果我有这样一个场景:

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从未发布事件,则永远不会调用done()方法。另外,如果它不发布事件,我的测试怎么知道?看起来不会失败,Jasmine只会打印测试没有“expect”之类的内容


更新:我意识到我不需要done()函数,因为我现在正在每次测试之前重置测试台。但这仍然不能解决问题,因为如果一个可观测对象没有发射,测试就不会失败。

就像你提到的,我认为你可以利用
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
将不会被调用,测试将挂起,并出现
异步超时错误

以下是我完成测试的方式:

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();
});

我不知道为什么会这样,因为我认为可观察对象是异步的。但它似乎可以在不担心异步的情况下工作。也许我只是走运了,问题会在以后出现。

嗯,在发布序列上运行单元测试似乎不是一个好策略。难道没有其他方法可以知道一个可观测的物体从未触发过事件吗?看看这个,也许会有帮助。