gpt4 book ai didi

reactjs - 已使用 Enzyme 和 Sinon 调用 React 组件上的测试自定义方法

转载 作者:行者123 更新时间:2023-12-03 13:40:28 25 4
gpt4 key购买 nike

我想检查当单击组件上的按钮时,它会调用我创建的方法来处理单击。这是我的组件:

import React, { PropTypes, Component } from 'react';

class Search extends Component {

constructor(){
super();
this.state = { inputValue: '' };
}

handleChange = (e) => {
this.setState({ inputValue: e.target.value });
}

handleSubmit = (e) => {
e.preventDefault();
return this.state.inputValue;
}

getValue = () => {
return this.state.inputValue;
}

render(){
return (
<form>
<label htmlFor="search">Search stuff:</label>
<input id="search" type="text" value={this.state.inputValue} onChange={this.handleChange} placeholder="Stuff" />
<button onClick={this.handleSubmit}>Search</button>
</form>
);
}
}

export default Search;

这是我的测试

  import React from 'react';
import { mount, shallow } from 'enzyme';
import Search from './index';
import sinon from 'sinon';

describe('Search button', () => {

it('calls handleSubmit', () => {
const shallowWrapper = shallow(<Search />);
const stub = sinon.stub(shallowWrapper.instance(), 'handleSubmit');
shallowWrapper.find('button').simulate('click', { preventDefault() {} });
stub.called.should.be.true();
});

});

名为 property 的调用返回 false。我已经尝试了很多语法变化,我想也许我只是错过了一些基本的东西。任何帮助将不胜感激。

最佳答案

我对诗乃也比较陌生。我通常将 spy() 传递到组件 props 中,并检查它们(尽管您可以以相同的方式使用 stub() ):

let methodSpy = sinon.spy(),
wrapper = shallow(<MyComponent someMethod={methodSpy} />)

wrapper.find('button').simulate('click')

methodSpy.called.should.equal(true)

我指出这一点是因为我认为这是对组件进行单元测试的最直接的方法(测试内部方法 can be problematic )。

在您的示例中,您尝试测试组件的内部方法,这是行不通的。我遇到了this issue不过,这应该可以帮助你。尝试:

it('calls handleSubmit', () => {
const shallowWrapper = shallow(<Search />)
let compInstance = shallowWrapper.instance()

let handleSubmitStub = sinon.stub(compInstance, 'handleSubmit');
// Force the component and wrapper to update so that the stub is used
compInstance.forceUpdate()
shallowWrapper.update()

shallowWrapper.find('button').simulate('click', { preventDefault() {} });

handleSubmitStub.called.should.be.true();
});

关于reactjs - 已使用 Enzyme 和 Sinon 调用 React 组件上的测试自定义方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39809046/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com