I'm trying to use test framework Jest with Next.js and styled-jsx.
This is my external css style.
import css from 'styled-jsx/css';
export const TextStyle = css`
p {
font-size: 14px;
color: #a8a8a8;
}
`;
and this is my package.json script. It works well.
"test": "jest --verbose",
I want to use coverage option. so I tried this "test": "jest --coverage --verbose"
, but it is not working.
ReferenceError: css is not defined
I have read this https://github.com/zeit/styled-jsx/issues/436. However, the issue is still open and doesn't help me.
How can I fix it?
styled-jsx
docs mention how to solve it but that didn't work well for me.
I made it work by doing the following:
Set the node env in your package.json
test scripts to "test" like so (can add the --verbose
flag as well if you want):
"test": "NODE_ENV=test jest",
"test:coverage": "NODE_ENV=test jest --coverage"
In your babel configuration (.babelrc
in my case) add babel-test: true
to the test
env config like so (refer to the Next
docs for more details):
{
// 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
}
}
]
]
}
}
}
Your tests should now pass but may show a warning saying:
styled-jsx/css: if you are getting this error it means that your
css tagged template literals were not transpiled.
In that case you should add a jest
auto mock for styled-jsx/css
by adding a new file with this exact path from the root of your project (the __mocks__
folder has to be a sibling of your node_modules
folder) /__mocks__/styled-jsx/css.js
:
function css() {
return ""
}
module.exports = css
*Note: what this whole setup does is disable styled-jsx transpilation when you run your tests which means that the generated classes will not be generated in your test components. In my case for example that breaks my tests because I'm relying on the generated classes for hiding some elements and my tests rely on those elements being hidden. I'm now trying to figure out a way around that but it may not be an issue in your case.