Next.js应用Jest + React Testing Library测试框架(下)

75 阅读2分钟

Next.js应用Jest + React Testing Library测试框架(上)

优化覆盖率测试报告阅读体验

在根目录下的testing-utils创建coverageShow.js并粘贴如下内容

const childProcess = require('child_process');
const fs = require('fs');
const path = require('path');

const filePath = path.resolve(__dirname, '../coverage/lcov-report/index.html');

const isOkToOpenPage = () => {
  return new Promise((resolve, reject) => {
    fs.access(filePath, fs.constants.F_OK, (err) => {
      if (err) {
        reject('覆盖率文件不存在');
      } else {
        resolve();
      }
    });
  });
};

isOkToOpenPage()
  .then(() => {
    childProcess.exec(`start ${filePath}`);
  })
  .catch((msg) => {
    console.error(msg);
  });

修改package.json的test:coverage指令

{
  "scripts": {
    "test:coverage": "jest --coverage && node ./testing-utils/coverageShow.js"
  },
}

完成此项修改即可在运行npm run test:coverage后,在网页上看到覆盖率报告

eslint插件

运行如下命令

npm install --save-dev eslint-plugin-jest-dom

在.eslintrc.js中添加如下配置

module.exports = {
  overrides: [
    {
      files: ['**/tests/**/*.[jt]s?(x)'],
      plugins: ["jest-dom"],
      extends: ["plugin:jest-dom/recommended"],
    },
  ],
};

如果有这种报错

0:0  error  Parsing error: ESLint was configured to run on `<tsconfigRootDir>/tests\xxxx\index.test.tsx` using `parserOptions.project`: <tsconfigRootDir>/tsconfig.json
However, that TSConfig does not include this file. Either:
- Change ESLint's list of included files to not include this file
- Change that TSConfig to include this file
- Create a new TSConfig that includes this file and include it in your parserOptions.project
See the typescript-eslint docs for more info: https://typescript-eslint.io/linting/troubleshooting#i-get-errors-telling-me-eslint-was-configured-to-run--however-that-tsconfig-does-not--none-of-those-tsconfigs-include-this-file

则在tsconfig.json添加如下配置

{
  "include": ["__tests__/**/*.ts", "__tests__/**/*.tsx"],
}

测试规则是否生效

在tests文件夹下新建a.js,并粘贴如下内容

const { getByRole } = render(<input type="checkbox" che />);
const element = getByRole("checkbox");
expect(element).toHaveProperty("checked"); // passes

(() => {
  const { getByRole } = render(<input type="checkbox" />);
  const element = getByRole("checkbox");
  expect(element).toHaveProperty("checked"); // also passes
})()

运行npx eslint ./__tests__如果出现如下报错,说明规则生效

xxxx\__tests__\a.js
  2:55  error  Unknown property 'che' found                            react/no-unknown-property
  4:19  error  Use toBeChecked() instead of toHaveProperty("checked")  jest-dom/prefer-checked
  5:5   error  Missing semicolon                                       @babel/semi
  9:17  error  Use toBeChecked() instead of toHaveProperty("checked")  jest-dom/prefer-checked

✖ 4 problems (4 errors, 0 warnings)
  3 errors and 0 warnings potentially fixable with the `--fix` option.

eslint-plugin-testing-library需要^18.18.0, ^20.9.0, or >=21.1.0版本的Node,如果当前项目使用的node版本不够高可以不用装这个。

参考链接

使用 React Testing Library 的 15 个常见错误
覆盖率报告
eslint-plugin-jest-dom
eslint-plugin-testing-library