我只是嘗試了茉莉節點。我需要一些有關承諾解決的幫助。我有簡單的JS文件如何使用jasmine-node測試函數,該函數內部調用返回promise的函數?
//dataService.js
var Q = require('q');
console.info("Q is "+Q);
exports.test = function() {
console.warn("Will call promise now");
this.getQuestions().then(function() {
console.log("Test..");
});
};
exports.getQuestions = function() {
var deferred = Q.defer();
for(i=0; i<=10; i++) {
if(i===10) {
deferred.resolve(i);
}
}
return deferred.promise;
// return {
// 'Question1': 'What is your name'
// }
}
//end of dataService.js
And the test is
// testspec.js
var assert = require("assert");
var q = require('q');
var testFile = require('../routes/dataService');
var fs = require('fs');
describe('#indexOf()', function(done){
it('should return -1 when the value is not present', function(done){
console.log("Teststststst" + fs);
assert.equal(-1, [1,2,3].indexOf(5));
assert.equal(-1, [1,2,3].indexOf(0));
spyOn(testFile, 'getQuestions').andCallFake(function() {
console.warn("Spy Called********************");
var deferred = q.defer();
deferred.resolve(1);
console.info("passing 1****");
//done(1);
return deferred.promise;
});
spyOn(console, 'log');
testFile.test();
console.info("Testststststsinggggggggg");
expect(console.log).toHaveBeenCalledWith("Test..");
console.info("Done*****************");
})
});
//測試文件的末尾現在
,你可以看到我打電話testFile.test()函數,它只不過是在dataService.js測試功能。這個函數調用dataService.js(同一個文件)中的getQuestions(),它返回一個promise。我在我的測試中嘲笑了getQuestions()函數,它正在調用並解決承諾,但我的test()成功方法沒有被調用,所以我的測試失敗了。
嘿,我<10爲i <= 10,這是一個錯字.....對不起..... ..測試不工作....實際上我已經窺探了getQuestions .....並且spied方法正在調用....但測試方法成功方法並未被調用 –