Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
355 views
in Technique[技术] by (71.8m points)

javascript - 如何使用Jasmine测试调用异步函数的函数(How to test a function which calls async function using Jasmine)

How to test this function:(如何测试此功能:)

var self = this; self.someVariable = "initial value"; self.test = function() { self.functionWhichReturnsPromise().then(function() { self.someVariable = "new value"; }); } I have test case like below, I know it is wrong because before promise is resolved, the assert statement will be executed by jasmine:(我有如下测试用例,我知道这是错误的,因为在答应解决之前,assert语句将由茉莉花执行:) it("should test the function test", function (done) { var abc = new ABC(); abc.test(); expect(abc.someVariable).toBe('new value'); }); Note that I do not want to use setTimeout() or any sleep methods.(请注意,我不想使用setTimeout()或任何睡眠方法。)   ask by Mumzee translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Two things, you need your test function to return the Promise and you need to use an arrow function or .bind the callback to the parent function (otherwise the this in this.someVariable will refer to the callback function):(有两件事情,你需要你的test函数return的承诺,你需要使用一个箭头功能或.bind回调到母函数(否则thisthis.someVariable将参照回调函数):)

this.test = function() { return this.functionWhichReturnsPromise().then(() => { this.someVariable = "new value"; }); } or(要么) this.test = function() { return this.functionWhichReturnsPromise().then(function() { this.someVariable = "new value"; }.bind(this)); } Then in your test you can do:(然后在测试中,您可以执行以下操作:) it("should test the function test", function (done) { var abc = new ABC(); abc.test().then(function() { expect(abc.someVariable).toBe('new value'); done(); }); });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...