reactjs - 如何测试是否调用了useState或单击了按钮?
问题描述
我一直在尝试找到一种方法来在一个简单的tsx
文件上获得 100% 的覆盖率,而唯一告诉我需要覆盖率的两行是我传递一个执行setState
from的回调的地方useState
。
我读过我不应该测试钩子,因为用户只关心 UI。这就是为什么我的问题是关于如何测试这两条线。
function App(): JSX.Element {
const [step, setStep] = React.useState(0);
return (
<main className={style.app}>
<Grid className={style.header} centerAlign>
<button
id="home-button"
className={style.headerHomeBtn}
onClick={() => setStep(0)}
>
<img className={style.headerHome} src={home} alt="home button" />
</button>
<h1>Financial Advisor</h1>
</Grid>
{step === 0 && <RiskSelector continue={() => setStep(1)} />}
{step === 1 && <Portfolio />}
</main>
);
}
Uncovered line #s: 18-24
哪些是onClick
和continue
道具。到目前为止,我的测试是:
describe('Dummy', () => {
let wrapper: any;
const setState = jest.fn();
const useStateMock: any = (initState: any) => [initState, setState];
beforeEach(() => {
wrapper = shallow(<Dummy />);
});
afterEach(() => {
jest.clearAllMocks();
});
describe('Home button clicked', () => {
it('calls setStep with 0', () => {
jest.spyOn(React, 'useState').mockImplementation(useStateMock);
console.log(wrapper.debug());
wrapper.find('button').props().onClick();
expect(setState).toHaveBeenCalled();
});
});
});
控制台输出只是告诉我按钮在那里。
测试未通过,因为setState
从未调用过。
解决方案
您不应该模拟React.useState()
钩子,并测试事件处理程序的实现细节。您应该测试组件的行为。行为是,例如,当状态改变时,视图会发生什么。
例如
App.tsx
:
import { Grid } from './Grid';
import React from 'react';
import { RiskSelector } from './RiskSelector';
import { Portfolio } from './Portfolio';
const home = 'http://localhost:3000/home.png';
export function App(): JSX.Element {
const [step, setStep] = React.useState(0);
return (
<main>
<Grid centerAlign>
<button id="home-button" onClick={() => setStep(0)}>
<img src={home} alt="home button" />
</button>
<h1>Financial Advisor</h1>
</Grid>
{step === 0 && <RiskSelector continue={() => setStep(1)} />}
{step === 1 && <Portfolio />}
</main>
);
}
Grid.tsx
:
import React from 'react';
export function Grid({ children, centerAlign }) {
return <div>{children}</div>;
}
Portfolio.tsx
:
import React from 'react';
export function Portfolio() {
return <div>Portfolio</div>;
}
RiskSelector.tsx
:
import React from 'react';
export function RiskSelector({ continue: onContinue }) {
return <div onClick={onContinue}></div>;
}
App.test.tsx
:
import React from 'react';
import { App } from './App';
import { shallow } from 'enzyme';
import { Portfolio } from './Portfolio';
import { RiskSelector } from './RiskSelector';
describe('67412919', () => {
let wrapper: any;
beforeEach(() => {
wrapper = shallow(<App />);
});
afterEach(() => {
jest.clearAllMocks();
});
describe('Home button clicked', () => {
it('calls setStep with 0', () => {
wrapper.find('button').simulate('click');
expect(wrapper.find(RiskSelector)).toHaveLength(1);
});
it('calls setStep with 1', () => {
wrapper.find(RiskSelector).invoke('continue')();
expect(wrapper.find(Portfolio)).toHaveLength(1);
expect(wrapper.find(RiskSelector)).toHaveLength(0);
});
});
});
文件覆盖率 100% 的单元测试结果App.tsx
。
PASS examples/67412919/App.test.tsx (7.433 s)
67412919
Home button clicked
✓ calls setStep with 0 (24 ms)
✓ calls setStep with 1 (12 ms)
------------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
------------------|---------|----------|---------|---------|-------------------
All files | 84.21 | 100 | 50 | 84.21 |
App.tsx | 100 | 100 | 100 | 100 |
Grid.tsx | 66.67 | 100 | 0 | 66.67 | 4
Portfolio.tsx | 66.67 | 100 | 0 | 66.67 | 3
RiskSelector.tsx | 66.67 | 100 | 0 | 66.67 | 4
------------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 7.958 s, estimated 8 s
推荐阅读
- django - 如何在 Django 测试中正确结束后台芹菜工作者
- python - 将字符串转换为 json,其中一些值包含在方括号中
- python - Tkinter 应用程序在其他屏幕中移动或通过 ssh 运行时不保持比例
- sql - 表上的 SQL 连接
- node.js - 为什么 Google Cloud Vision API 的节点客户端不考虑纵横比
- java - 如何修复从静态方法问题引用的非静态?
- asp.net-mvc - MiniProfiler ASP.NET MVC5 无法获得结果
- c# - 为什么我不能在进程启动中放入 3 个变量?
- postgresql - 在没有 docker 的情况下将 PostgreSQL 数据库链接到 PostgREST
- servicenow - 将 servicenow 与 Aws cloudwatch 事件集成