我正在尝试使用Jasmine测试REST api调用。任何人都可以解释如何使用Jasmine来处理这样的异步测试吗?
============================== answer.js ============== ================
var conf = require('../config');
var req = require('request');
var fs = require('fs');
function base64_encode(file) {
var file = fs.readFileSync(file);
return new Buffer(file).toString('base64');
}
var answers = function (){
this.getAnswer = function(id, branchId, locale, question, deviceId){
var answer;
req({
url : conf.baseUrl + '/api/v1/answers',
method : 'POST',
headers: {
'content-type': 'text/plain',
},
body : JSON.stringify({
id : id,
branchId : branchId,
locale : locale,
question : base64_encode("./" + question + ".wav"),
deviceId : deviceId
})
}, function(error, response, body) {
if (error) {
console.log(error);
} else {
answer = JSON.parse(body).answer;
console.log(JSON.parse(body).responseText);
fs.writeFile("../answer.wav", answer, 'base64',
function(err) {
if (err) {
return console.log(err);
}
console.log("file saved successfully!");
});
}
});
return answer;
}
}
module.exports = new answers();
======================= loan_application_spec.js ===================== =
var answers_api = require('../requests/answers');
describe("Loan application", function() {
it("Ask about loans", function() {
console.log(answers_api.getAnswer("1234", "HLB_02", "en-US", "input", "robot_01"));
});
});
答案 0 :(得分:0)
以下是我对其进行修改以适应测试的方法。
这是帮助我构建这个答案的post。
var conf = require('../config');
var req = require('request');
var fs = require('fs');
function base64_encode(file) {
var file = fs.readFileSync(file);
return new Buffer(file).toString('base64');
}
var answers = {
ans: "",
getAnswer : function(id, branchId, locale, question, deviceId){
var answer;
req({
url : conf.baseUrl + '/api/v1/answers',
method : 'POST',
headers: {
'content-type': 'text/plain',
},
body : JSON.stringify({
id : id,
branchId : branchId,
locale : locale,
question : base64_encode("./" + question + ".wav"),
deviceId : deviceId
})
}, function(error, response, body) {
if (error) {
console.log(error);
} else {
answer = JSON.parse(body).answer;
console.log(JSON.parse(body).responseText);
fs.writeFile("../answer.wav", answer, 'base64',
function(err) {
if (err) {
return console.log(err);
}
console.log("file saved successfully!");
});
}
});
this.ans = answer;
return answer;
}
}
return module.exports = Object.create(answers);
//Jasmine test
var answers_api = require('../requests/answers');
describe("Loan application", function() {
it("Ask about loans", function() {
req = jasmine.createSpy().andCallFake(function() {
answers_api.ans = true // actually make this answer whatever you expect it to be.
});
var testObj = answers_api.getAnswer("1234", "HLB_02", "en-US", "input", "robot_01"));
expect(req).toHaveBeenCalled();
expect(answers_api.ans).toBe(true)
});
});