简体   繁体   English

承诺回调中的单元测试逻辑

[英]Unit testing logic inside promise callback

I have an ES6 / Aurelia app that I am using jasmine to test. 我有一个正在使用茉莉花测试的ES6 / Aurelia应用程序。 The method I am trying to test looks something like this: 我尝试测试的方法如下所示:

update() {
    let vm = this;
    vm.getData()
        .then((response) => {
            vm.processData(response);
        });
}

Where this.getData is a function that returns a promise. 其中this.getData是一个返回诺言的函数。

My spec file looks something like this: 我的规格文件看起来像这样:

describe('my service update function', () => {
    it('it will call the other functions', () => { 
        myService = new MyService();
        spyOn(myService, 'getData').and.callFake(function() {
            return new Promise((resolve) => { resolve(); });
        });
        spyOn(myService, 'processData').and.callFake(function() { return; });
        myService.update();

        // this one passes
        expect(myService.getData).toHaveBeenCalled();

        // this one fails
        expect(myService.processData).toHaveBeenCalled();
    });
});

I understand why this fails - promises are asynchronous and it hasn't been resolved by the time it hits the expect. 我知道为什么会失败-承诺是异步的,并且在达到期望时尚未解决。

How can I push the promises to resolve from my test so that I can test the code inside the call back? 我如何才能将承诺从测试中分解出来,以便可以在回调中测试代码?

jsfiddle of failed test: http://jsfiddle.net/yammerade/2aap5u37/6/ 失败的jsfiddle: http : //jsfiddle.net/yammerade/2aap5u37/6/

I got a workaround running by returning an object that behaves like a promise instead of an actual promise 我通过返回一个行为类似于承诺而不是实际承诺的对象来解决问题

describe('my service update function', () => {
    it('it will call the other functions', () => { 
        myService = new MyService();
        spyOn(myService, 'getData').and.returnValue({
            then(callback) {
                callback();
            }
        });
        spyOn(myService, 'processData').and.callFake(function() { return; });
        myService.update();

        // this one passes
        expect(myService.getData).toHaveBeenCalled();

        // this one fails
        expect(myService.processData).toHaveBeenCalled();
    });
});

Fiddle here: http://jsfiddle.net/yammerade/9rLrzszm/2/ 在这里提琴: http : //jsfiddle.net/yammerade/9rLrzszm/2/

Is there anything wrong with doing it this way? 这样做有什么问题吗?

it((done) => {
  // call done, when you are done
  spyOn(myService, 'processData').and.callFake(function() {
    expect(myService.processData).toHaveBeenCalled();

    done();
  });
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM