I'm trying to run a simple Jest test against React/Mobx code that just render a route and checks if it was rendered. I don't use classes and Mobx decorators. I receive an error on every place where I wrap my component with Mobx observer
function:
const MyComp: React.FC = observer(() => {...})
My Jest config:
module.exports = {
"testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js|jsx)$",
"moduleFileExtensions": [
"ts",
"tsx",
"js"
],
"roots": ['<rootDir>'],
"modulePaths": ['<rootDir>'],
"moduleDirectories": [
".",
"src",
"node_modules"
],
"setupFiles": [
"raf/polyfill",
"<rootDir>/jest.setup.js"
],
"snapshotSerializers": [
"enzyme-to-json/serializer"
],
"testPathIgnorePatterns": [
"<rootDir>/node_modules/"
],
"transform": {
"\\.(ts|tsx)$": "ts-jest",
"\\.js$": "babel-jest",
'^.+.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2|mp4)$': 'jest-transform-stub',
'^.+\\svg': 'jest-svg-transformer',
'^.+\\inline.svg': 'jest-svg-transformer'
},
"moduleNameMapper": {
"mobx": "<rootDir>/node_modules/mobx",
'^.+.(css|styl|less|sass|scss|png|jpg|ttf|woff|mp4|woff2)$': 'jest-transform-stub',
'^.+\\svg': 'jest-svg-transformer',
'^.+\\inline.svg': 'jest-svg-transformer'
},
"coverageReporters": [
"html", "text"
]
}
My test case:
describe('General:', () => {
test('landing page renders ok', async () => {
render((
<ThemeProvider theme={ theme }>
{ renderRoutes(routes) }
</ThemeProvider>
), { wrapper: BrowserRouter });
await screen.findByText('Correct text here')
})
});
I tried keep everything the same and just removed mobx observer
wrapper from a component and all works fine with absolutely the same setup.
The Jest documentation about moduleNameMapper
states that:
Note: If you provide module name without boundaries
^$
it may cause hard to spot errors. E.g.relay
will replace all modules which containrelay
as a substring in its name:relay
,react-relay
andgraphql-relay
will all be pointed to your stub.
You have mobx
in your moduleNameMapper
which will stub out both mobx
and mobx-react
, which is not what you want. You should be able to get rid of the error by removing that.