我的组件具有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

最佳答案

这是基于@skyboyer的解释的单元测试解决方案。

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

07-25 21:48