styled-jsx 文档提到了如何解决它,但这对我来说效果不佳。
我通过执行以下操作使其工作:将package.json测试脚本中的节点环境设置为“测试”,就像这样(--verbose如果需要,也可以添加标志):
"test": "NODE_ENV=test jest",
"test:coverage": "NODE_ENV=test jest --coverage"
在你的 babel 配置中(.babelrc在我的例子中)像这样添加babel-test: true到testenv 配置中(有关更多详细信息,请参阅Next 文档):
{
// this is your original config, it's required if you don't have a babel config yet and are using `Next` since `Next` normally does it under the hood for you:
"presets": [
[
"next/babel",
]
],
// this is what you're adding:
"env": {
"test": {
"presets": [
[
"next/babel",
{
"styled-jsx": {
"babel-test": true
}
}
]
]
}
}
}
您的测试现在应该通过了,但可能会显示一条警告:
styled-jsx/css: if you are getting this error it means that your css tagged template literals were not transpiled.
在这种情况下,您应该通过从项目的根目录添加一个具有此确切路径的新文件来添加jest自动模拟(该文件夹必须是您文件夹的同级):styled-jsx/css__mocks__node_modules/__mocks__/styled-jsx/css.js
function css() {
return ""
}
module.exports = css
*注意:整个设置的作用是在您运行测试时禁用 styled-jsx 转换,这意味着生成的类将不会在您的测试组件中生成。例如,在我的情况下,这会破坏我的测试,因为我依赖于生成的类来隐藏某些元素,而我的测试依赖于那些被隐藏的元素。我现在正想办法解决这个问题,但在您的情况下可能不是问题。