styled-jsx
文档提到了如何解决它,但这对我来说效果不佳。
我通过执行以下操作使其工作:将package.json
测试脚本中的节点环境设置为“测试”,如下所示(--verbose
如果需要,也可以添加标志):
"test": "NODE_ENV=test jest",
"test:coverage": "NODE_ENV=test jest --coverage"
在您的 babel 配置中(.babelrc
在我的情况下)添加babel-test: true
到test
env 配置中,如下所示(有关更多详细信息,请参阅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 转换,这意味着生成的类不会在您的测试组件中生成。例如,在我的情况下,这会破坏我的测试,因为我依赖生成的类来隐藏某些元素,而我的测试依赖于隐藏的那些元素。我现在正试图找出解决方法,但在你的情况下这可能不是问题。