Ria
Ria

Reputation: 2100

Mock exported function in module

I have two modules which contain exported functions. "ModuleB" uses a function from "ModuleA". Now I want to test "ModuleB" and mock the used function from "ModuleA".

I use ES6 with babel. For testing I use karma and jasmine.

I tried using babel-rewire and inject-loader, but it just does not work. I'm kind of new to all this and I guess I'm just doing something wrong. So any help is appreciated!

moduleA.js

export function getResult() {
    return realResult;
}

moduleB.js

import * as ModuleA from './moduleA'

export function functionToTest() {
    let result = ModuleA.getResult();
    // do stuff with result which I want to test
}

my test

it("does the right thing", () => {
    // I tried using rewire, but this gives me an exception:
    ModuleB.__Rewire__('ModuleA', {

        getResult: () => {
            return fakeResult;
        }
    });

    let xyz = ModuleB.functionToTest(canvas, element);
});

Upvotes: 0

Views: 866

Answers (2)

Ria
Ria

Reputation: 2100

For anyone who is interested in how it works with babel-rewire: The trick is to use __RewireAPI__.

import * as ModuleB from '../ModuleB'
import {__RewireAPI__ as ModuleBRewire} from '../ModuleA';

it("does the right thing", () => {
    let moduleAMock = {
        getResult: () => {
            return fakeResult;
        }
    }

    ModuleBRewire.__Rewire__('ModuleA', moduleAMock);

    let xyz = ModuleB.functionToTest();
});

Upvotes: 0

damianfabian
damianfabian

Reputation: 1681

Take a look to this library https://www.npmjs.com/package/mockery I thought It's exactly what do you want. Hope it helps!

EDITED:

Basically you have to use mockery in each test to mock your function, the only problem is that you must use require against import with the modules you want to mock. Look this example:

const moduleUnderTest = './moduleB.js';
const moduleA_fake = { getResult: () => { return "This is a fake result"; } } ;

describe("Mocking functions", () => {

    it('Should be Fake Result', (done) => {

        mock.registerAllowable(moduleUnderTest);
        mock.registerMock('./moduleA.js', moduleA_fake);

        mock.enable({ useCleanCache: true });

        let ModuleB = require(moduleUnderTest);
        let res = ModuleB.functionToTest();

        res.should.be.eql("This is a fake result");


        mock.disable();
        mock.deregisterAll();

        done();
    });

    it('Should be Real Result', (done) => {

        let ModuleB = require(moduleUnderTest);
        let res = ModuleB.functionToTest();

        res.should.be.eql("real foo");

        done();
    });

});

You could see the complete example Here

Upvotes: 1

Related Questions