【发布时间】:2019-06-15 20:25:53
【问题描述】:
我正在尝试测试使用“easy-soap-request”库的函数。 我想模拟“soapRequest”函数返回的结果。
我尝试了this,但没有成功,我不断从外部 API 获取数据。
client.js
const soapRequest = require('easy-soap-request');
async function get_data(){
var response = await soapRequest(url, auth_headers) //this is what I want to mock
var result;
result = some_parsing_function(response); //this is what I want test
return result;
}
test.js
const client = require('../../client');
describe('get_data tests', () =>{
it('should test sth', function (done) {
var stubed = stub(client, 'soapRequest').returns('dummy value');
client.get_data().then((result) => {
//assertions
console.log(result) //result still has value from external service
done();
});
})
});
编辑:
所以我尝试按照其中一个答案的建议使用 sinon.fake()。
const client = require('../../client');
describe('get_data tests', () =>{
it('should test sth', function (done) {
var fake_soap = fake(async () => {
return 12345;
});
replace(cilent, 'soapRequest', fake_soap);
client.soapRequest().then((res) => {
console.log(res); // 12345
})
client.get_data().then((result) => {
//assertions
console.log(result) //still original value from external service
done();
});
})
});
【问题讨论】:
-
使用mock-module等来模拟一个模块。这是诗浓一个人做不到的。
标签: javascript node.js unit-testing ecmascript-6 sinon