gpt4 book ai didi

javascript - 检查 Jest 中功能组件的状态值

转载 作者:行者123 更新时间:2023-12-02 21:50:42 27 4
gpt4 key购买 nike

我的组件有一个状态(特殊),我如何在我的测试用例中检查这个状态值?

组件.jsx

      export function SearchProviders({ changeRoute }) {
const [speciality, setspeciality] = useState("Hospital");
// blah blah blah
}

测试.jsx

const renderedModule = shallow(<SearchProviders />);
const speciality = renderedModule.find('#speciality');
speciality.simulate('change');
console.log(renderedModule.state('speciality'));

我尝试这样做,但它给我错误说 state() 只能在类组件上调用

最佳答案

这是基于@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

关于javascript - 检查 Jest 中功能组件的状态值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60135675/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com