有没有办法在Jest中测试组件中的自定义错误,而不会在控制台中抛出Uncaught错误?
这里我有一个简单的按钮组件:
import React from 'react';
export default class Button extends React.Component {
render() {
if (!this.props.type) {
throw new Error('Button requires a type prop');
}
return (
<button className={`btn btn-${this.props.type}`}>Button</button>
);
}
}
Run Code Online (Sandbox Code Playgroud)
在不提供type属性的情况下使用组件时,我希望抛出自定义错误.我也有以下Jest测试:
import React from 'react';
import ReactDOM from 'react-dom';
import Button from './button';
it('throws an error if the type prop is not defined', () => {
const buttonType = undefined;
const container = document.createElement('div');
expect(() => {
ReactDOM.render(<Button type={buttonType} />, container);
}).toThrow('Button requires a type prop'); …Run Code Online (Sandbox Code Playgroud) window.location是一个对象.但是当你执行location.toString()它时,将对象转换为等效的对象location.href.
我的问题是怎么样?我可以将对象设置为类似的行为吗?
我试图监视由另一个函数调用的函数,这两个函数都驻留在外部文件中并导入。
Funcs.spec.js:
import * as Funcs from './Funcs'
describe('funcA', () => {
it('calls funcB', () => {
jest.spyOn(Funcs, 'funcB')
Funcs.funcA()
expect(Funcs.funcB).toHaveBeenCalled()
}
}
Run Code Online (Sandbox Code Playgroud)
Funcs.js:
export const funcA = () => {
funcB()
}
export const funcB = () => {}
Run Code Online (Sandbox Code Playgroud)
出于某种原因,间谍在 Funcs.js 的范围内不受尊重。我可以做什么来监视 funcB 以便我知道 funcA 调用了它?