【问题标题】:Simulate change on input does not call a function模拟输入变化不调用函数
【发布时间】:2021-08-06 10:24:01
【问题描述】:

我正在学习用 React 编写单元测试。测试应该检查当输入字段发生变化时是否调用了 onChange 函数。这是我的简单搜索栏组件:

import {Input} from './Input';

const SearchBar = (props) => {
  return (
    <Input 
      type="search"
      data-test="search"
      onChange={e => props.onSearch(e.target.value)} />
  );
};

export default SearchBar;

我写的测试应该模拟输入字段的变化,然后应该调用函数调用。

describe('Search', () => {
  afterEach(() => {
    jest.clearAllMocks();
  });

  it('Should call onSearch function', () => {
    const wrapper = mount(<SearchBar onSearch={onSearch}/>);
    const searchBar = wrapper.find('[data-test=search]').at(0);
    searchBar.simulate('change', {target: { 'test' }});
    expect(onSearch).toBeCalledTimes(1);
  });
});

这里,函数根本没有被调用,而不是被调用 1 次。我不知道为什么。你能解释一下我在哪里做错了吗?

【问题讨论】:

    标签: reactjs unit-testing testing jestjs enzyme


    【解决方案1】:

    您应该使用jest.fn() 创建一个模拟的onSearch。 CSS 选择器应该是'[data-test="search"]'

    例如

    SearchBar.tsx:

    import React from 'react';
    
    function Input(props) {
      return <input {...props} />;
    }
    
    const SearchBar = (props) => {
      return <Input type="search" data-test="search" onChange={(e) => props.onSearch(e.target.value)} />;
    };
    
    export default SearchBar;
    

    SearchBar.test.tsx:

    import { mount } from 'enzyme';
    import React from 'react';
    import SearchBar from './SearchBar';
    
    describe('Search', () => {
      afterEach(() => {
        jest.clearAllMocks();
      });
    
      it('Should call onSearch function', () => {
        const onSearch = jest.fn();
        const wrapper = mount(<SearchBar onSearch={onSearch} />);
        const searchBar = wrapper.find('[data-test="search"]').at(0);
        searchBar.simulate('change', { target: { value: 'test' } });
        expect(onSearch).toBeCalledTimes(1);
      });
    });
    

    测试结果:

     PASS  examples/68669299/SearchBar.test.tsx (7.33 s)
      Search
        ✓ Should call onSearch function (47 ms)
    
    ---------------|---------|----------|---------|---------|-------------------
    File           | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
    ---------------|---------|----------|---------|---------|-------------------
    All files      |     100 |      100 |     100 |     100 |                   
     SearchBar.tsx |     100 |      100 |     100 |     100 |                   
    ---------------|---------|----------|---------|---------|-------------------
    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        8.002 s, estimated 9 s
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-04
      相关资源
      最近更新 更多