mardi 5 mars 2019

JavaScript / Mocha - How to test if function was called with await

I would like to write a test that check if my function calls other functions using the await keyword.

I'd like my test to fail:

async methodA() {
   this.methodB();
},

I'd like my test to succeed:

async methodA() {
   await this.methodB();
},

I have a solution by stubbing the methods and force them return with fake promises inside them using process.nextTick, but it seems to be ugly, and I do not want to use process.nextTick nor setTimeout etc in my tests.

ugly-async-test.js

const { stub } = require('sinon');
const { expect } = require('chai');

const testObject = {
    async methodA() {
        await this.methodB();
    },
    async methodB() {
        // some async code
    },
};

describe('methodA', () => {
    let asyncCheckMethodB;

    beforeEach(() => {
        asyncCheckMethodB = stub();
        stub(testObject, 'methodB').returns(new Promise(resolve => process.nextTick(resolve)).then(asyncCheckMethodB));
    });

    afterEach(() => {
        testObject.methodB.restore();
    });

    it('should await methodB', async () => {
        await testObject.methodA();
        expect(asyncCheckMethodB.callCount).to.be.equal(1);
    });
});

What is the smart way to test if await was used in the function call?

Aucun commentaire:

Enregistrer un commentaire