javascript - 如何模拟异步函数的返回值?
问题描述
我正在尝试测试使用“easy-soap-request”库的函数。我想模拟“soapRequest”函数返回的结果。
我已经尝试过了,但没有成功,我不断从外部 API 获取数据。
客户端.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;
}
测试.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();
});
})
});
解决方案
在源文件中,soapRequest
变量本身是一个函数而不是命名的导入(对象) ,因此不可能仅依赖sinon.stub
.
如果看一下easy-soap-request
源代码,显然它会导出一个函数https://github.com/circa10a/easy-soap-request/blob/master/index.js#L14
根据我的经验,对于这种情况,可以通过添加proxyquire
如下来解决。
const proxyquire = require('proxyquire');
const sinon = require('sinon');
// we mock `easy-soap-request` (the library name) by using `sinon.stub`
const client = proxyquire('../../client', { 'easy-soap-request': sinon.stub().returns('dummy value') })
describe('get_data tests', () =>{
it('should test sth', async () => { // use async/await for better code
const result = await client.get_data();
console.log(result); // dummy value
})
});
如果你不想使用sinon
,你也可以这样做
const client = proxyquire('../../client', { 'easy-soap-request': () => 'dummy value' })
参考:
https://www.npmjs.com/package/proxyquire
希望能帮助到你
推荐阅读
- node.js - 使用 Puppeteer 时提取的 HTML 与等效屏幕截图不匹配
- android - 应用程序在断开呼叫 webRTC android 时崩溃
- javascript - 在javascript中计算平均值后如何存储一位小数
- r - 逻辑回归中的不同梯度计算
- c# - 如何在 C# 中停止/取消复制过程
- laravel - 如何在laravel中为面包屑编写路线?
- javascript - 在不改变形状的情况下将任何 SVG 路径分割成片段
- ios - 资源超过 iOS 13 上的最大大小
- git - 当我尝试从 azure git 进行 git clone 时如何进行身份验证?
- python-3.x - Flask 配置错误导致站点拒绝连接