我正在尝试针对 React/Mobx 代码运行一个简单的 Jest 测试,该代码仅渲染路由并检查它是否已渲染。我不使用类和 Mobx 装饰器。我在使用 Mobx observer
函数包装组件的每个地方都会收到错误:
const MyComp: React.FC = observer(() => {...})
我的 Jest 配置:
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"
]
}
我的测试用例:
describe('General:', () => {
test('landing page renders ok', async () => {
render((
<ThemeProvider theme={ theme }>
{ renderRoutes(routes) }
</ThemeProvider>
), { wrapper: BrowserRouter });
await screen.findByText('Correct text here')
})
});
我尝试保持所有内容相同,只是从组件中删除了 mobx observer
包装器,并且在完全相同的设置下一切正常。
- mobx:6.4.0
- mobx-react:7.5.0
- 开 Jest :26.6.3
最佳答案
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.
您的 moduleNameMapper
中有 mobx
,它将同时删除 mobx
和 mobx-react
,即不是你想要的。您应该能够通过删除该错误来消除该错误。
关于reactjs - Jest/React/Mobx : TypeError mobxReact. 观察者不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65278357/