反应单元测试匿名函数

问题描述 投票:2回答:1

我正在尝试测试onChange匿名函数,该函数会更改文本框中的值。我想验证如果onChange内部的函数被调用,状态是否已更改。该函数本身很简单:

onChange={(e) => this.setState({someState: e.value})}

如果函数具有名称,我将执行以下操作:

         test('myFunction should change someState value', () => {

                 const wrapper = shallow(<MyComponent/>);
                 const instance = wrapper.instance();

                const mockEvent = {
                    target:{
                        value: "some value in textbox"
                     }        
                   };

                const expectedValue = "some value in textbox";

                instance.myFunction(mockEvent);
                expect(wrapper.state().someState).toEqual(expectedValue)

              }); 

由于该函数是匿名的,所以我不知道如何用实例调用它。我不想给函数命名,因为我不想测试影响我的代码。有什么好的解决方案?

javascript reactjs unit-testing jestjs enzyme
1个回答
1
投票

有两种方法可以测试这种情况。例如:

index.tsx

import React, { Component } from 'react';

export default class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      someValue: '',
    };
  }
  render() {
    return (
      <>
        <input type="text" onChange={(e) => this.setState({ someValue: e.target.value })}></input>
      </>
    );
  }
}

index.test.tsx

import MyComponent from './';
import { shallow } from 'enzyme';
import React from 'react';

describe('61597604', () => {
  it('should pass', () => {
    const wrapper = shallow(<MyComponent></MyComponent>);
    const mEvent = { target: { value: 'ok' } };
    wrapper.find('input').simulate('change', mEvent);
    expect(wrapper.state()).toEqual({ someValue: 'ok' });
  });

  it('should pass 2', () => {
    const wrapper = shallow(<MyComponent></MyComponent>);
    const input = wrapper.find('input').getElement();
    const mEvent = { target: { value: 'ok' } };
    input.props.onChange(mEvent);
    expect(wrapper.state()).toEqual({ someValue: 'ok' });
  });
});

具有100%覆盖率的单元测试结果:

 PASS  stackoverflow/61597604/index.test.tsx (8.059s)
  61597604
    ✓ should pass (13ms)
    ✓ should pass 2 (1ms)

-----------|---------|----------|---------|---------|-------------------
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:        9.213s
© www.soinside.com 2019 - 2024. All rights reserved.