gpt4 book ai didi

reactjs - 如何在 ReactJS 组件单元测试中获取 'mock' 状态值?

转载 作者:行者123 更新时间:2023-12-03 13:31:16 37 4
gpt4 key购买 nike

我正在尝试对我的 ReactJS 组件进行单元测试。基本上它是一个由输入和按钮组成的简单组件。单击按钮时,它会触发一个名为“onSave”的事件,并且仅当 state.textValue 不为空时才会调用“this.props.addTodo”:

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

export default class Invoer extends Component {

static propTypes = {
saveTodo: PropTypes.func.isRequired
}

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


onChange = (event) => {
if (event.target.value !== '') {
this.setState({textValue: event.target.value});
console.log(event.target.value);
}
}

onSave = () => {
if (this.state.textValue!== '') {
this.props.saveTodo(this.state.textValue);
}
}

render() {
return (
<header>
<input type="text" value={this.state.textValue} onChange={this.onChange}/>
<button onClick={this.onSave}>save</button>
</header>
);
}
}

我为 onSave 事件编写了一个单元测试。唯一的问题是我无法弄清楚如何“模拟” this.state.textValue 以便设置第 26 行上的状态,请参见上面:

import React from 'react';
import Invoer from "../components/Invoer";
import {createRenderer} from 'react-test-renderer/shallow';
it('should call this.props.saveTodo event when clicking on button on non empty value', () => {
const props = {
saveTodo: jest.fn()
}

const renderer = createRenderer();
renderer.render(<Invoer {...props} />)
const output = renderer.getRenderOutput()

//tried to mock the state.textValue, results in error:
//output.props.children[0].value = 'hoera';

output.props.children[1].props.onClick();

expect(props.saveTodo).toBeCalled()
});

运行此测试时,我收到此错误:

should call this.props.saveTodo event when clicking on button on non empty value
expect(jest.fn()).toBeCalled()
Expected mock function to have been called.

这当然是预料之中的。我怎样才能“模拟”这个 this.state.textValue ?或者这是完全错误的方法?

最佳答案

对于遇到这个问题的其他人(我假设OP现在已经解决了这个问题)-如果使用enzyme您可以直接在组件上调用 setState:

// assuming props and mockState are set in a beforeEach()
it('adds state to the component', () => {
const myComponent = shallow(<MyComponent {...props} />);
myComponent.setState({ ...mockState });
const instance = myComponent.instance();
expect(instance.state).toEqual(mockState);

// you can then directly call instance methods - e.g. mocking
// previous props/state to test changes are handled as expected
instance.componentDidUpdate(prevProps, prevMockState);
});

请注意,根据您的要求,您可能需要使用 mount() 而不是 shallow()

关于reactjs - 如何在 ReactJS 组件单元测试中获取 'mock' 状态值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46315640/

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