Jest.js React组分酶试验(浅)

nzrxty8p  于 2023-09-28  发布在  Jest
关注(0)|答案(1)|浏览(143)

我想测试一个简单的react组件。它通过props接收回调。

<AnimalSelector onSearchTermChange={Search} />

如下所示:

import React, { Component } from 'react';
class SexSelector extends Component {
    constructor(props){
    super(props);
    this.state = {sex: ''};
}
render(){
    return (<div>
<input type="radio" name="sex" value="male" id="male" checked={this.state.sex === 'male'} onChange={event => this.onInputChange(event.target.value)} /> 
<label>Male</label>  
<input type="radio" name="sex" value="female" id="female" checked={this.state.sex === 'female'} onChange={event => this.onInputChange(event.target.value)} /> 
<label>Female</label>
</div>);        
}
onInputChange(animal){
    this.setState({sex});
    this.props.onSearchTermChange(sex);
}   
};
export default SexSelector

我写了一个简单的测试来检查选项何时更改:

import React from 'react';
import ReactDOM from 'react-dom';
import renderer from 'react-test-renderer';
import {shallow} from 'enzyme';
import SexSelector from '../components/animal_selector';
it('male option changes state sex to male', () => {
const wrapper = shallow(<SexSelector onSearchTermChange="void()"/>); 
// manually trigger the callback
wrapper.instance().onInputChange('male');
expect(wrapper.state().sex).toBe('male');
});

但是,测试运行器会引发以下错误:
TypeError:this.props.onSearchTermChange不是函数
at SexSelector.onInputChange(src/components/sex_selector.js:20:15)
at Object.(src/test/sexSelector.test.js:31:22)
at node_modules/p-map/index.js:42:16
at process._tickCallback(node.js:369:9)
Jest/Enzyme是否可以在没有父组件的情况下测试组件?哪种方法是绕过回调的正确方法?这是正确的做法吗?

vqlkdk9b

vqlkdk9b1#

我想"void()"只是要呈现为字符串。不是空函数。不管怎样,这都不是最好的办法。
与其这样,不如派个间谍下去。
我在这里使用expect assertions来创建间谍,你可以使用sinon或者任何你想要的东西。

import React from 'react';
import ReactDOM from 'react-dom';
import renderer from 'react-test-renderer';
import {shallow} from 'enzyme';
import SexSelector from '../components/animal_selector';
import expect from 'expect';

it('male option changes state sex to male', () => {
    const spy = expect.createSpy();
    const wrapper = shallow(<SexSelector onSearchTermChange={spy} />); 
    const maleInput = wrapper.find('#male');
    const mockEvent = {};

    maleInput.simulate('change', mockEvent);

    expect(wrapper.state().sex).toBe('male');
    expect(spy).toHaveBeenCalledWith(mockEvent);
});

相关问题