1

I have the following module called index.js

export function iWantToMockThis(a) {
    return a + 1;
}

export function foo(a) {
    return iWantToMockThis(a);
}

and the following test

import {foo} from '../src/index';

describe("testing mock es6", () => {
    jest.doMock('../src/index', () => ({
        foo: jest.requireActual('../src/index').foo,
        iWantToMockThis: jest.fn(() => 99)
    }));

    test('mocking barProp', ()=> {
        expect(foo(2)).toBe(99); // <-- it should be 99 but its 3
    })

});

This is just a small example of what I'm trying to achieve a bigger scale, by design iWantToMockThis has to be in the same module, but I do not find the way to mock it and return what I want to the foo method.

Any idea?

Some context:

  • I tried many things, eg jest.mock before the es6 import.
  • Default jest configuration

complete example: https://github.com/juanpicado/jest_mock_es6_example

Juan Picado
  • 1,823
  • 18
  • 33
  • 1
    It's impossible to spy or mock an export that is used within same module. – Estus Flask Sep 08 '18 at 12:27
  • You are right, here the why https://github.com/facebook/jest/issues/1075#issuecomment-221771095 – Juan Picado Sep 10 '18 at 11:45
  • 1
    Yes, this isn't specific to Jest. Possible workarounds are listed in dupe questions. Basically, you need to either move functions to separate modules or assign them to some object and use as methods. Or skip a mock if it's not vital for testability. – Estus Flask Sep 10 '18 at 11:52
  • Yes, It's what I did, actually, it's much better testable in that way. Thanks for pointing me in the right direction. – Juan Picado Sep 10 '18 at 11:54

0 Answers0