【发布时间】:2022-01-15 00:39:24
【问题描述】:
我正在使用Jest 对我的一个组件运行单元测试,但遇到了一些错误。
我尝试测试的组件使用tinymce,因此,我从tinymce 导入了一些文件。我在我的setupTests.js 文件中插入了以下内容的官方 Jest 文档中看到:
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: jest.fn().mockImplementation(query => ({
matches: false,
media: query,
onchange: null,
addListener: jest.fn(), // Deprecated
removeListener: jest.fn(), // Deprecated
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
dispatchEvent: jest.fn(),
})),
});
但是,我已经这样做了,但我遇到了另一个问题:
Jest 遇到了意外的令牌 SyntaxError: Unexpected token '.'
导入“tinymce/skins/ui/oxide.skin.min.css”
我尝试遵循使用“moduleNameMapper”模拟来自 Tinymce 的所有内容以及模拟非 JS 模块的建议。例如,我的_jest.config.js 文件包括:
module.exports = {
"moduleNameMapper": {
"^image![a-zA-Z0-9$_-]+$": "GlobalImageStub",
"^[./a-zA-Z0-9$_-]+\\.png$": "<rootDir>/RelativeImageStub.js",
"module_name_(.*)": "<rootDir>/substituted_module_$1.js",
"assets/(.*)": [
"<rootDir>/images/$1",
"<rootDir>/photos/$1",
"<rootDir>/recipes/$1"
]
}
"transformIgnorePatterns": [
"<rootDir>/node_modules/"
]
}
以上不起作用,我仍然得到同样的错误。
编辑:
根据其中一个建议,我创建了一个 styleMock.js 文件,其中包含 module.exports = {}; 并包含在我的 src/tests/jest/__mocks__ 路径中。然后我输入了:
"moduleNameMapper": {
'\\.(css|less)$': '<rootDir>/src/tests/jest/__mocks__/styleMock.js'
}
但我仍然遇到与上述相同的错误。
【问题讨论】:
-
您没有在
moduleNameMapper中包含.css扩展名,并且 jest 正在尝试将 CSS 文件作为 JS 文件导入,这会导致该错误。也许here 的答案之一会有所帮助 -
谢谢。即使我创建了一个导出空对象的
styleMock.js,并按照答案建议在我的jest.config.js文件中添加moduleNameMapper,我仍然遇到同样的错误。我已经编辑了我的问题以反映这一点。
标签: css reactjs unit-testing jestjs