[Bug] Unable to mock default exported Component when same module also has named export
See original GitHub issueDo you want to request a feature or report a bug? Bug
What is the current behavior? I have an ES6 module that exports a React Component class by default, but also exports a plain JS function as a named export. When testing other packages that use this module, I want to mock both the default exported component and named exported function to keep my unit tests pure.
The module looks something like this:
import React, { Component } from 'react';
export default class MyComponent extends Component {
render() {
return <div>Hello</div>
}
}
export function myUtilityFunction() { return 'foo' };
I would like to use the following syntax to mock the exports:
import React from 'react';
import MyComponent, { myUtilityFunction } from './module';
jest.mock('./module');
MyComponent.mockImplementation(() => 'MockComponent');
myUtilityFunction.mockImplementation(() => 'foo');
When I try to use this syntax, however, MyComponent
does not appear to be mocked when used within other components. When I try to mock MyComponent
like this and render it on its own, it renders out to null.
This behavior is very strange, because if I use the exact same syntax, but both imports are JavaScript functions, the mocking works as expected. See the StackOverflow issue I opened here that confirms that the syntax works when the imports are both functions.
Here is a GitHub repo demoing the problem, as well as several solutions I’ve tried: https://github.com/zpalexander/jest-enzyme-problem
What is the expected behavior?
I should be able to import the default exported component and the named exported function into my test file, and mock both using jest.mock('path')
and the .mockImplementation()
method.
Please provide your exact Jest configuration and mention your Jest, node, yarn/npm version and operating system.
See this repo for an exact reproduction: https://github.com/zpalexander/jest-enzyme-problem
You can build the repo and run the tests with yarn install && yarn test
Thanks!
Issue Analytics
- State:
- Created 6 years ago
- Comments:5 (1 by maintainers)
Top GitHub Comments
For others, this helped me out:
To follow up, the solution I ended up using was:
The solution that @joaovieira posted works as well.
Hopefully Jest can eventually provide users with a mocking API that requires less boilerplate.