Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.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
在TypeScript/JavaScript代码的单元测试中,如何等待内部订阅事件触发?_Javascript_Unit Testing_Jasmine_Rxjs5_Typescript2.0 - Fatal编程技术网

在TypeScript/JavaScript代码的单元测试中,如何等待内部订阅事件触发?

在TypeScript/JavaScript代码的单元测试中,如何等待内部订阅事件触发?,javascript,unit-testing,jasmine,rxjs5,typescript2.0,Javascript,Unit Testing,Jasmine,Rxjs5,Typescript2.0,我有两个类,MyService和FooComponent,如下所示: class MyService { getStuff(): Observable<Any> () { //Implementation that may take sometime to return } } class FooComponent { private myServiceSubscription: Subscription; public FooMod

我有两个类,MyService和FooComponent,如下所示:

class MyService {
    getStuff(): Observable<Any> () {
        //Implementation that may take sometime to return
    }
}

class FooComponent {
    private myServiceSubscription: Subscription;
    public FooModel : MyDateType;

    constructor(private myService: MyService){
        this.FooModel = null;
        this.myServiceSubscription = null;
    }

    Init() {
        this.myServiceSubscription = this.myService.getStuff().subscribe(response => {
            //Construct this.FooModel from response;
        }
    }

    Done() {
        if (this.myServiceSubscription !== null) {
            myServiceSubscription.unsubscribe();
        }
    }
}
此测试总是失败,因为测试不会等到FooComponent的Init方法中触发subscribe事件,因此不会填充FooComponent实例FooModel


我该怎么做才能知道测试如何等待subscribe事件触发并填充FooModel?

您应该使用@Jin建议的存根。最简单的方法:

fdescribe('Component: Foo', () => {

    it('Load Foo Model', (() => {

        var myService = jasmine.createSpyObj('myService', ['getStuff']);
        myService.getStuff.and.callFake(() => {
            return Observable.of(/* response */);
        });

        var instance = new FooComponent(myService);
        instance.Init();

        if (instance.FooModel == null)
        {
            fail("FooModel is null even after calling Init() method.");
        }
    }));

});

如果您同步地从
getStuff
返回值,那么
Init
中的回调也将被同步调用,并且不需要使用超时或其他东西。

我认为您应该看看对MyService的模仿不是问题。问题是如何向外部世界发出内部订阅事件已触发的信号。
fdescribe('Component: Foo', () => {

    it('Load Foo Model', (() => {

        var myService = jasmine.createSpyObj('myService', ['getStuff']);
        myService.getStuff.and.callFake(() => {
            return Observable.of(/* response */);
        });

        var instance = new FooComponent(myService);
        instance.Init();

        if (instance.FooModel == null)
        {
            fail("FooModel is null even after calling Init() method.");
        }
    }));

});