如何使用Jasmine测试调用异步函数的函数

Mum*_*zee 2 javascript jquery promise jasmine

如何测试这个功能:

var self = this;
self.someVariable = "initial value";
self.test = function() {
   self.functionWhichReturnsPromise().then(function() {
     self.someVariable = "new value";
   });
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

Rob*_* M. 6

有两件事,你需要你的test函数到returnPromise,你需要使用箭头函数或.bind回调父函数(否则thisin this.someVariable将引用回调函数):

this.test = function() {
   return this.functionWhichReturnsPromise().then(() => {
     this.someVariable = "new value";
   });
}
Run Code Online (Sandbox Code Playgroud)

要么

this.test = function() {
   return this.functionWhichReturnsPromise().then(function() {
     this.someVariable = "new value";
   }.bind(this));
}
Run Code Online (Sandbox Code Playgroud)

然后在你的测试中你可以做到:

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