2017-08-11 40 views
2

如何测试这个功能异步函数功能:如何测试它要求使用茉莉花

var self = this; 
self.someVariable = "initial value"; 
self.test = function() { 
    self.functionWhichReturnsPromise().then(function() { 
    self.someVariable = "new value"; 
    }); 
} 

我有测试用例就像下面,我知道这是错误的,因为之前承诺解决,assert语句会由茉莉花执行:

it("should test the function test", function (done) { 
    var abc = new ABC(); 
    abc.test(); 
    expect(abc.someVariable).toBe('new value'); 
}); 

请注意,我不想使用setTimeout()或任何睡眠方法。

回答

4

两件事情,你需要你的test功能return的承诺,你需要使用一个箭头功能或.bind回调到父功能(否则this.someVariablethis将把回调函数):

this.test = function() { 
    return this.functionWhichReturnsPromise().then(() => { 
    this.someVariable = "new value"; 
    }); 
} 

this.test = function() { 
    return this.functionWhichReturnsPromise().then(function() { 
    this.someVariable = "new value"; 
    }.bind(this)); 
} 

然后在您的测试,你可以这样做:

it("should test the function test", function (done) { 
    var abc = new ABC(); 
    abc.test().then(function() { 
     expect(abc.someVariable).toBe('new value'); 
     done(); 
    }); 
}); 
+1

我已经编辑了问题,所以剩下的唯一的事情就是从'test'函数返回的承诺。假设我不能编辑'test'函数来返回promise,那么是否还有一种方法来测试变量'someVariable'? – Mumzee

+0

如果你不能退还承诺,那么没有'setTimeout'没有办法准确地测试这个。 –

+0

忘记调用'done'。 –

0

现在asyncawait可在茉莉花。你可以用它们来测试你的异步函数天气的承诺或可观察。

it("should test the function test", async (done) => { 
    var abc = new ABC(); 
    abc.test(); 
    expect(await abc.someVariable).toBe('new value'); // await will wait until abc.someVariable resolved or rejected 
}); 

我在角4应用测试在使用asyncawait,它应该为你工作。

1

你可以窥探返回承诺的函数。

describe('when test method', function() { 
    beforeEach(function() { 
    this.promiseResult = Math.random(); 
    spyOn(ABC.prototype, 'functionWhichReturnsPromise') 
     .and.returnValue(Promise.resolve(this.promiseResult)); 
    }) 

    it('then should change someVariable with the result of functionWhichReturnsPromise', function() { 
    var abc = new ABC(); 
    abc.test(); 
    expect(abc.someVariable).toBe(this.promiseResult); 
    }); 
}); 

无需等待的承诺,这个单元测试里面,你不感兴趣的functionWhichReturnsPromise如何实际工作,你只希望看到调用functionWhichReturnsPromise的结果将更新someVariable值。

有乐趣和好运