繁体   English   中英

React 单元测试匿名 function

[英]React unit testing anonymous function

我正在尝试测试一个 onChange 匿名 function,它会更改我的文本框中的值。 我想验证是否调用了 onChange 中的 function ,是否更改了 state 。 function 本身很简单:

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

如果 function 有名称,我会执行以下操作:

         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)

              }); 

由于 function 是匿名的,我不知道如何用实例调用它。 我不想给 function 一个名字,因为我不希望测试影响我的代码。 什么是好的解决方案?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM