Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock return value of async function?

I'm trying to test function which uses 'easy-soap-request' library. I want to mock results returned by 'soapRequest' function.

I've tried this but it didn't worked, I keep getting data from external 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();
        });

    })
});

EDIT:

So I've tried using sinon.fake() as suggested by one of the answers.

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();
        });

    })
});
like image 590
PTW Avatar asked Nov 06 '22 21:11

PTW


1 Answers

In the source file, soapRequest variable itself is a function not a named import (object) so it is impossible to rely on just sinon.stub.

If take a look at easy-soap-request source code, obviously, it exports a function https://github.com/circa10a/easy-soap-request/blob/master/index.js#L14

Based on my experience, for this case, it can be solved by adding proxyquire like below.

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
    })
});

If you don't want to use sinon, you can also do this

const client = proxyquire('../../client', { 'easy-soap-request': () => 'dummy value' })

Reference:

https://www.npmjs.com/package/proxyquire

Hope it helps

like image 111
deerawan Avatar answered Nov 12 '22 14:11

deerawan