I'm requiring invariant in my tested code like so:
var invariant = require('react/lib/invariant');
In my tests, 'req/lib/invariant' does not get mocked, even when I explicitly call jest.mock('react/lib/invariant')
To get around this unexpected behavior, I require('./invariant'), which looks like this:
module.exports = require('react/lib/invariant');
Is there any way to require('sub/modules')?
I have the same problem. Is there any progress?
is it still an issue?
i just ran
var invariant = require('fbjs/lib/invariant');
describe('invariant', function() {
it('is mocked', function() {
expect(invariant._isMockFunction).toBe(true);
});
});
and it worked
I'm going to have a look at the thing today in the evening. Nevertheless, I think the problem has gone because jest was rewritten, particularly a mocking part.
Hi @dmitriiabramov, I've created a repo where you can reproduce the problem: https://github.com/ivantsov/jest-mock-nested-folders. Just run npm i & npm test.
There is a __mocks__ folder with sdk folder and foo.js file inside but Jest fails with error Cannot find module 'sdk/foo' from 'sample.js'.
Hope it helps.
@ivantsov i think the issue here is that you don't have the sdk module.
here is what i tried in your repo:
mkdir -p node_modules/sdk && echo "module.exports = function() { return 1; }" >> node_modules/sdk/foo.js
and the test passed
But if I just create sdk.js inside __mocks__ it'll work as expected, without actually having sdk module. This is why I think it's unexpected behavior...
that is true.. __mocks__/sdk.js worked, but __mocks__/sdk/foo.js didn't.
@cpojer any thoughts on that?
Yep, seems like any attempt to mock any require('module/submodule') mapped to mocks/module/submodule is failing on my side.
In the meantime I use jest.mock + require.requireActual
Yeah the solution here is to use jest.mock. We are unlikely to extend manual mocks to have sub folders for now but I might revisit this decision in the future.
Most helpful comment
Yeah the solution here is to use jest.mock. We are unlikely to extend manual mocks to have sub folders for now but I might revisit this decision in the future.