quickstart
<h1>说明</h1>
<p>Cypress Component Test (React)</p>
<p><a href="https://docs.cypress.io/guides/component-testing/overview">@cypress/react</a> library helps you test React components in isolation. It is one of the viable solutions for developing unit and integration testing. It mounts the target component(s) and executes tests in a browser context. Finally, there is a solution for running isolated tests much closer to the browser context. <a href="https://medium.com/geekculture/testing-mobx-store-with-react-cypress-made-it-easy-abc5b1571320">Abhinaba Ghosh</a></p>
<h2>1. quick_start</h2>
<h2>2. some useful skills</h2>
<h3>2.1 stub</h3>
<p>A stub is a way to modify a function and delegate control over its behavior to you (the programmer).
<a href="https://docs.cypress.io/guides/guides/stubs-spies-and-clocks#Spies" title="spy">stub</a> 是一种<strong>修改函数</strong>并将对其行为的控制委托给您(程序员)的方法</p>
<h3>2.2 spy</h3>
<p><a href="https://docs.cypress.io/guides/guides/stubs-spies-and-clocks#Spies" title="spy">spy</a> 使您能够<strong>“监视”一个函数</strong>,让您捕获并断言该函数是用正确的参数调用的,或者该函数被调用了一定次数,甚至是返回值是什么或者调用函数的上下文</p>
<h2>3. 实际项目中配置组件测试</h2>
<ol>
<li>pull 项目代码</li>
<li>安装依赖包
<pre><code>npm install 或
yarn</code></pre></li>
<li>安装cypress
<pre><code>npm install --save-dev cypress 或
yarn add -D cypress</code></pre>
<p>一般要与项目所用命令相同</p></li>
<li>打开cypress
<pre><code>npx cypress open</code></pre>
<p>在打开的页面中'component test' >> 一直下一步 >> 。。。
此时才会在根目录下生成cypress 文件夹和cypress.config.ts 配置文件</p></li>
<li>添加配置文件
在 cypress 目录下添加如下配置文件
<pre><code>{
"compilerOptions": {
// "target": "es5",
// "lib": ["es5", "dom"],
"esModuleInterop": true
"jsx": "react-jsx",
"types": ["cypress"]
},
// "include": ["**/*.ts", "**/*.tsx", "../cypress.d.ts"]
"include": ["**/*.ts", "**/*.tsx"]
}</code></pre></li>
<li>写测试用例
可以在cypress 文件夹下新建 component 文件夹,用于存放测试用例
测试用例要以 <strong>.cy.tsx</strong> 结尾</li>
<li>测试文件示例
<pre><code>import React from 'react'; // 此语句为必填项
import NotFound from '../../src/components/NotFound'
describe('ComponentName.cy.ts', () => {
it('playground', () => {
cy.mount(<NotFound />)
cy.get('div').should('have.class','modular_not_found');
})
})</code></pre></li>
</ol>
<h1>4. Reference</h1>
<p>[1.] <a href="https://docs.cypress.io/guides/component-testing/react/quickstart#Getting-Started">quick start </a>
[2.] <a href="https://docs.cypress.io/api/commands/mount">cy.mount</a>
[3.] <a href="https://docs.cypress.io/guides/component-testing/react/examples">React Examples</a></p>