rewire seems to break `import * as foo from 'module'`
Closed this issue · 1 comments
I've just introduced babel-plugin-rewire into my repo so I can test my non-exported functions. Sounds great.
But I have lots of jest tests broken because of the following test scenario, which i've dumbed down to reproduce the problem.
module1.js
const getMessageText = () => {
return 'this is text from myFunc';
};
export { getMessageText };
module2.js
import { getMessageText } from './module1';
const testFunc = () => {
return getMessageText();
};
export { testFunc };
What I want to do in my test, is:
- check to see that the named export getMessageText() was called when testFunc was called.
- mock out getMessageText() to return a different outcome.
./__tests__/module2.test.js
import { testFunc } from '../module2';
import * as allFuncs from '../module1';
describe('should be able to check the mock', () => {
const spy = jest
.spyOn(allFuncs, 'getMessageText')
.mockImplementation(() => 'overridden text');
test('make sure spy gets executed', () => {
const result = testFunc();
expect(spy).toHaveBeenCalled();
expect(result).toEqual('overridden text');
});
});
If I run the test without babel-plugin-rewire, I get this:
> npx jest module2
PASS client src/jest-test/__tests__/module2.test.js
should be able to check the mock
✓ make sure spy gets executed (4ms)
If I run the test with babel-plugin-rewire, I get this:
> npx jest module2
FAIL client src/jest-test/__tests__/module2.test.js
should be able to check the mock
✕ make sure spy gets executed (4ms)
● should be able to check the mock › make sure spy gets executed
expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0
9 | test('make sure spy gets executed', () => {
10 | const result = testFunc();
> 11 | expect(spy).toHaveBeenCalled();
| ^
12 | expect(result).toEqual('overridden text');
13 | });
14 | });
at Object.toHaveBeenCalled (src/client/modules/jest-test/__tests__/module2.test.js:11:21)
I have tried so many workarounds but I just can't find one that works, and I wonder if this is a bug with babel-plugin-rewire.
No responses. Never mind. Closing.
And no, I never got to resolve it.
I think the issue is to do with referencing. Once the module is "rewired" then the "spy" has to spy on the rewired module, not the original module... or something like that.