问题:
我有一个简单的 React 组件,我正在使用它来学习使用 Jest 和 Enzyme 测试组件。在处理 Prop 时,我添加了 prop-types
模块来检查开发中的属性。 prop-types
使用 console.error
在未传递必需的 props 或 props 是错误的数据类型时发出警报。
我想模拟 console.error
来计算它在我传入丢失/错误输入的 props 时被 prop-types
调用的次数。
使用这个简化的示例组件和测试,我希望这两个测试的行为如下:
- 具有 0/2 个所需 Prop 的第一个测试应该捕获模拟调用两次。
- 具有 1/2 必需 Prop 的第二个测试应该捕获调用一次的模拟。
相反,我得到了这个:
- 第一个测试运行成功。
- 第二个测试失败,提示 mock 函数被调用了零次。
- 如果我调换测试顺序,第一个有效,第二个失败。
- 如果我将每个测试拆分成一个单独的文件,那么两者都有效。
console.error
输出被抑制,所以很明显它被模拟了。
我确信我遗漏了一些明显的东西,比如清除模拟错误或其他什么。
当我对导出函数的模块使用相同的结构时,调用 console.error
任意次数,一切正常。
当我用 enzyme / react 进行测试时,我在第一次测试后就碰壁了。
示例 App.js:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
export default class App extends Component {
render(){
return(
<div>Hello world.</div>
);
}
};
App.propTypes = {
id : PropTypes.string.isRequired,
data : PropTypes.object.isRequired
};
示例 App.test.js
import React from 'react';
import { mount } from 'enzyme';
import App from './App';
console.error = jest.fn();
beforeEach(() => {
console.error.mockClear();
});
it('component logs two errors when no props are passed', () => {
const wrapper = mount(<App />);
expect(console.error).toHaveBeenCalledTimes(2);
});
it('component logs one error when only id is passed', () => {
const wrapper = mount(<App id="stringofstuff"/>);
expect(console.error).toHaveBeenCalledTimes(1);
});
最后说明:是的,最好编写组件以在缺少 props 时生成一些用户友好的输出,然后对其进行测试。但是一旦我发现了这种行为,我就想弄清楚我做错了什么,以此来提高我的理解力。显然,我遗漏了什么。
最佳答案
我遇到了类似的问题,只是需要缓存原来的方法
const original = console.error
beforeEach(() => {
console.error = jest.fn()
console.error('you cant see me')
})
afterEach(() => {
console.error('you cant see me')
console.error = original
console.error('now you can')
})
关于javascript - Jest : mocking console. 错误 - 测试失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44596915/