编程语言
首页 > 编程语言> > javascript – 如何模拟异步函数的返回值?

javascript – 如何模拟异步函数的返回值?

作者:互联网

我正在尝试测试使用’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();
        });

    })
});

解决方法:

在源文件中,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

希望能帮助到你

标签:javascript,node-js,unit-testing,ecmascript-6,sinon
来源: https://codeday.me/bug/20190705/1387252.html