【发布时间】:2020-02-02 19:35:24
【问题描述】:
尝试使用模拟函数与基本的 React 应用程序一起进行简单的测试,但它失败了,我无法确定哪里出错了。谁能直截了当?
主 App.js
import React, { Component } from 'react';
import './App.css';
import List from './List';
class App extends Component {
state = {
count: 0,
newItem: '',
items: ['apple', 'milk']
}
addItem = () => {
if (this.state.newItem) {
this.setState({ count: this.state.count + 1, items: [...this.state.items, this.state.newItem], newItem: '' })
}
}
render() {
return(
<div className="App">
<header className="App-header">
<h1>30 days of React</h1>
<h2>Day Thirty / Testing React Components</h2>
<p>Total Items: {this.state.count}</p>
</header>
<div className="container">
<input type='text' value={this.state.newItem} onChange={e => this.setState({ newItem: e.target.value})}></input>
<button className='main-btn' onClick = {this.addItem}>Add To List</button>
</div>
<div>
<List items={this.state.items}/>
</div>
</div>
)
}
}
export default App;
测试
//define empty mock function to simulate the click
const mockClick = jest.fn();
describe('App component mock test', () => {
it('button click should fire function', () => {
const component = shallow(<App onClick={mockClick} />);
const input = component.find('input');
input.simulate('change', {target: {value: 'test'} });
const button = component.find('button.main-btn');
button.simulate('click');
expect(mockClick).toHaveBeenCalled();
});
});
还有一个呈现列表的功能组件,但由于这是一个肤浅的测试,它不应该发挥作用。
【问题讨论】:
-
你的组件没有使用 any 的 props,不清楚你为什么期望
mockClick被调用。实际行为是在List中显示的项目中添加一个新项目,您应该对此进行测试(检查List的道具,潜水或使用更深的渲染)。 -
因为没有点击按钮?这只是一个让我了解如何测试的项目,我意识到这不是一个真实的案例等等......在我确定这个更基本的渲染之后,将继续测试更深层次的渲染以准确地测试这个:)跨度>
-
但是,既然从未访问过,为什么还要为
App组件调用this.props.onClick? -
抱歉,“访问”具体是什么意思?到目前为止,感谢您的帮助:)
-
我不知道该怎么说。参考?你在 App 的什么地方使用了它的 props?