Unit testing logic inside promise callback

Deadly 提交于 2019-12-22 12:23:24

问题


I have an ES6 / Aurelia app that I am using jasmine to test. 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.

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/


回答1:


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/

Is there anything wrong with doing it this way?




回答2:


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

    done();
  });
})


来源:https://stackoverflow.com/questions/42727660/unit-testing-logic-inside-promise-callback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!