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

时间:2020-02-09 10:33:13

标签: javascript reactjs ecmascript-6 jestjs enzyme

我的组件有一个# this python snippet just generates the plot blow. import matplotlib.pyplot as plt # there are actually a lot more, ~10000 points. xs = [8.36, 1.14, 0.93, 8.55, 7.49, 6.55, 5.13, 8.49, 0.15, 3.48] ys = [0.65, 6.32, 2.04, 0.51, 4.5, 7.05, 1.07, 5.23, 0.66, 2.54] plt.xlim([0, 10]) plt.ylim([0, 10]) plt.plot(xs, ys, 'o') plt.show() (特殊性),我该如何在测试用例中检查此状态值?

component.jsx

state

Test.jsx

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

我曾这样尝试过,但是它给了我一个错误,说const renderedModule = shallow(<SearchProviders />); const speciality = renderedModule.find('#speciality'); speciality.simulate('change'); console.log(renderedModule.state('speciality'));

1 个答案:

答案 0 :(得分:1)

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