​ 最近项目上对UT coverage有要求。有同事推荐使用Cypress,因为它是运行在真实的浏览器环境中。而react testing library是基于jsdom,再加上因为我们项目中的组件库是基于web component的,所以会有很多shadow DOM的问题。

​ Cypress不仅可以做end-to-end test,还可以做unit test。我目前理解它的unit test是Component Test。接下来的步骤是在CRA的基础上setup Cypress的component test。

  1. 创建一个CRA的项目
    yarn create react-app react-cypress-demo

  2. 添加cypress相关依赖
    yarn add cypress @cypress/react @cypress/webpack-dev-server --dev

  3. 到目前为止,可以运行以下命令来生成cypress的configuration文件
    yarn cypress open-ct
    命令执行完后,在根目录会生成一个cypress.json文件和一个cypress的文件夹。

  4. cypress.json中添加如下配置,其中testFiles根据实际项目约定来定义即可。

    {
      "component": {
        "testFiles": "**/*.test.{js,ts,jsx,tsx}",
        "componentFolder": "src"
      }
    }
    
  5. cypress/plugins/index.js中添加如下配置。

    const injectDevServer = require("@cypress/react/plugins/react-scripts")
    
    module.exports = (on, config) => {
      injectDevServer(on, config)
      return config
    }
    

    以上就配置好了cypress环境。

    接下来可以基于App.js的现有内容将App.test.js用cypress改写如下。

import { mount } from '@cypress/react';
import App from './App';

it('renders learn react link', () => {
  mount(<App />);
  cy.get('a').contains('Learn React');
});

这时就可以运行yarn cypress open-ct来看UT的执行结果了,它会启动一个新的窗口,需要点击左边的spec,UT才会运行。

References:
Getting Started with Cypress Component Testing (React)
Component Test Introduction

Posted on 2021-06-26 13:02  單筱寒  阅读(234)  评论(0编辑  收藏  举报