我的组件有一个state(专业),我如何在我的测试用例中检查这个状态值?
component.jsx
export function SearchProviders({ changeRoute }) {
const [speciality, setspeciality] = useState("Hospital");
// blah blah blah
}Test.jsx
const renderedModule = shallow(<SearchProviders />);
const speciality = renderedModule.find('#speciality');
speciality.simulate('change');
console.log(renderedModule.state('speciality'));我试着这样做,但它给了我错误,说state() can only be called on class components
发布于 2020-02-11 15:34:58
这是基于@skyboyer的解释的单元测试解决方案。
不要测试onInputChange函数的实现细节。测试组件在调用后的变化。
更改可能是文本内容、组件结构等。
index.tsx
import React, { useState } from 'react';
export function SearchProviders({ changeRoute }) {
const [speciality, setspeciality] = useState('Hospital');
const onInputChange = () => {
setspeciality(speciality.toUpperCase());
};
return (
<div>
<span>{speciality}</span>
<input id="speciality" onChange={onInputChange}></input>
</div>
);
}index.test.tsx
import { SearchProviders } from './';
import React from 'react';
import { shallow, ShallowWrapper } from 'enzyme';
describe('60135675', () => {
let wrapper: ShallowWrapper;
beforeEach(() => {
const props = { changeRoute: jest.fn() };
wrapper = shallow(<SearchProviders {...props}></SearchProviders>);
});
it('should render', () => {
expect(wrapper.exists()).toBeTruthy();
expect(wrapper.find('span').text()).toBe('Hospital');
});
it('should handle input change', () => {
wrapper.find('#speciality').simulate('change');
expect(wrapper.find('span').text()).toBe('HOSPITAL');
});
});100%覆盖的单元测试结果:
PASS stackoverflow/60135675/index.test.tsx (6.152s)
60135675
✓ should render (11ms)
✓ should handle input change (2ms)
-----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
index.tsx | 100 | 100 | 100 | 100 |
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 8.217s源代码:https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/60135675
https://stackoverflow.com/questions/60135675
复制相似问题