reactjs - Jest/React/Mobx : TypeError mobxReact. 观察者不是函数

标签 reactjs jestjs mobx mobx-react ts-jest

我正在尝试针对 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 contain relay as a substring in its name: relay, react-relay and graphql-relay will all be pointed to your stub.

您的 moduleNameMapper 中有 mobx ,它将同时删除 mobxmobx-react,即不是你想要的。您应该能够通过删除该错误来消除该错误。

关于reactjs - Jest/React/Mobx : TypeError mobxReact. 观察者不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65278357/

相关文章:

javascript - jest.spyOn 不适用于解构函数

javascript - MobX 对象数组的深度自动运行

javascript - 如何在 Mobx 中执行可观察函数?

javascript - 如何在Interval React.js中乘以数字时获得索引0

javascript - 错误 : A React component suspended while rendering, 但未指定后备 UI

typescript - Jest&supertest API 测试返回 TypeError : app. 地址不是函数

reactjs - 开 Jest 不创建快照

reactjs - 如何使用CDN链接将库导入到reactjs中?

javascript - React Router - 无法读取未定义的属性 'history'

reactjs - 如何以 react 方式从 mobx observable 获取项目?