reactjs - Jest 和 Enzyme 失败的模拟函数
问题描述
尝试使用与基本 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();
});
});
还有一个呈现列表的功能组件,但由于这是一个肤浅的测试,它不应该发挥作用。
解决方案
好的,想通了。哦。基本上我只是对模拟的工作方式及其用例感到困惑。我现在明白了。创建了一个以 onCick 作为道具的子组件来简单地测试该函数是否正在触发,现在它正在工作。
测试
const mockClick = jest.fn();
describe('ListItem component mock tests', () => {
it('button click should fire function', () => {
const component = shallow(<ListItem onClick={mockClick} />);
const button = component.find('button.smallbtn');
button.simulate('click');
expect(mockClick).toHaveBeenCalled();
});
});
我正在测试的子组件
import React from 'react';
const ListItem = ( props ) => {
return (
<div>
<p>{props.item}</p>
<button className="smallbtn" onClick={() => props.onClick(props.id)}>delete</button>
</div>
);
};
export default ListItem;
推荐阅读
- python - 如何将非 SQLAlchemy 默认类型设置为 utf8 bin
- react-native - 如何在本机反应中从 responseJson 中删除 html 标签?
- javascript - 如何使用JS触发woocommerce产品库灯箱打开
- javascript - 为什么我需要使用 this.props.user.user.displayName 而不是 this.props.user.displayName?反应
- php - PHP 日期格式返回不正确的后缀 ('S')
- python - Python 解析 GitHub 文件
- outlook - iCal 文件不会将 VALARM 警报作为 Internet 日历导入 Outlook
- asp.net - System.Net.HttpWebRequest.GetResponse() 错误“您必须在调用 [Begin]GetResponse 之前将 ContentLength 字节写入请求流。”
- mule - Mule 3.9.1 数据库参数化查询不返回数据
- node.js - 错误:运行 jhipster 命令后 npm install 中 JSON 输入意外结束