如何在 Next.js styled-jsx 中使用 jest 覆盖? [英] How can I use jest coverage in Next.js styled-jsx?

查看:17
本文介绍了如何在 Next.js styled-jsx 中使用 jest 覆盖?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

这篇关于如何在 Next.js styled-jsx 中使用 jest 覆盖?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆