酶浅渲染:使用 'simulate' 时无法 trigger/assert 更改值
Enzyme shallow rendering: unable to trigger/assert value change when using 'simulate'
我真的很难弄清楚如何断言我可以在我的应用程序的输入字段中输入文本。在浏览器中,出现了预期的行为,即当我 select 并开始输入时文本出现在输入中。但是在我的测试中,期望没有返回 'a',而是收到了 'undefined'.
这是我的测试:
import React from 'react'
import { shallow } from 'enzyme';
import Search from './search';
describe('Search', () => {
const wrapper = shallow(<Search />);
it('renders without crashing', () => {
shallow(<Search />);
});
it('accepts text in an input', () => {
const input = wrapper.find('input');
input.simulate('change', { target: { value: 'a' } });
expect(input.props().value).toEqual('a');
});
});
和实施:
import React, { Component } from 'react';
class Search extends Component {
constructor(props) {
super(props);
this.state = {
searchText: "Roi"
};
}
inputUpdate (event) {
this.setState({ searchText: event.target.value});
}
render() {
return(
<form>
<input type="text"
className="card-search"
placeholder="Type card name"
onChange={ this.inputUpdate.bind(this) }
value={ this.state.searchText }/>
</form>
);
};
};
export default Search;
这快把我逼疯了,我确定我漏掉了一些简单的东西。有人可以帮我解释一下吗?
您的 inputUpdate
不会更新您的组件状态。试试这个:
inputUpdate (e) {
this.setState({
searchText: e.target.value
});
}
我不知道为什么会这样,但似乎是这样...
改变
expect(input.props().value).toEqual('a');
至
expect(wrapper.find('input').props().value).toEqual('a');
我真的很难弄清楚如何断言我可以在我的应用程序的输入字段中输入文本。在浏览器中,出现了预期的行为,即当我 select 并开始输入时文本出现在输入中。但是在我的测试中,期望没有返回 'a',而是收到了 'undefined'.
这是我的测试:
import React from 'react'
import { shallow } from 'enzyme';
import Search from './search';
describe('Search', () => {
const wrapper = shallow(<Search />);
it('renders without crashing', () => {
shallow(<Search />);
});
it('accepts text in an input', () => {
const input = wrapper.find('input');
input.simulate('change', { target: { value: 'a' } });
expect(input.props().value).toEqual('a');
});
});
和实施:
import React, { Component } from 'react';
class Search extends Component {
constructor(props) {
super(props);
this.state = {
searchText: "Roi"
};
}
inputUpdate (event) {
this.setState({ searchText: event.target.value});
}
render() {
return(
<form>
<input type="text"
className="card-search"
placeholder="Type card name"
onChange={ this.inputUpdate.bind(this) }
value={ this.state.searchText }/>
</form>
);
};
};
export default Search;
这快把我逼疯了,我确定我漏掉了一些简单的东西。有人可以帮我解释一下吗?
您的 inputUpdate
不会更新您的组件状态。试试这个:
inputUpdate (e) {
this.setState({
searchText: e.target.value
});
}
我不知道为什么会这样,但似乎是这样...
改变
expect(input.props().value).toEqual('a');
至
expect(wrapper.find('input').props().value).toEqual('a');