- document和window的方法可用jest.fn()模拟(例:`window.open is not a function`)
window.open = jest.fn();
document.execCommand = jest.fn();
- 列表页等具有多个查询条件的url,可用String.prototype.includes()来mock路径(例:`pages?per_page=10&page=1`)
if (url.includes('pages')) {}
- 因引用`~/vendor/Editor`所产生的警告可使用如下代码mock
jest.mock('~/vendor/Editor', () => {
return {
default: () => <div>Editor</div>
};
});
- 如Form是条件渲染,在调用setFieldsValue时引起的警告`You cannot set a form field before rendering a field associated with the value.`,可在setFieldsValue之前使用getFieldDecorator注册该属性
this.props.form.getFieldDecorator('range_type', { initialValue: '' });
this.props.form.setFieldsValue({ range_type: t });
- 在多个文件中都需要使用的mock,可在.jest/setup.js中添加mock,例
// Canvas
HTMLCanvasElement.prototype.getContext = () => {
return {
fillStyle: null,
fillRect: () => {},
drawImage: () => {},
clearRect: () => {},
getImageData: () => {},
putImageData: () => {},
createImageData: () => {},
setTransform: () => {},
save: () => {},
fillText: () => {},
restore: () => {},
beginPath: () => {},
moveTo: () => {},
lineTo: () => {},
closePath: () => {},
stroke: () => {},
translate: () => {},
scale: () => {},
rotate: () => {},
arc: () => {},
fill: () => {},
measureText: () => {},
transform: () => {},
rect: () => {},
clip: () => {}
};
};
- 组件中使用了history,单测
import createHistory from 'history/createBrowserHistory';
const history = createHistory({});
- 使用了有网络请求的公用组件,单测里面需要mock公共组件的网络请求数据 否则会报
- E?(else 情况没有写,以为这样就完了?jest会认为你没有覆盖else,扣你覆盖率) I?(没有执行后面代码,???,需要查看下为什么没有执行到,是不是有别的报错了),看下面
- 网络请求 else 如何覆盖? post(patch)方法会传参,根据参数修改mock数据的status,get(delete)方法会在url传参,url.indexOf('xxx')判断,从而修改mock的status,看实例
post: (url,data) => {
return {
then: cb => {
const status = data.id == '1' ? 200 : 500;
cb({
status: status,
data: {
errors: ['this is a error test!']
}
});
}
};
},
get: url => {
return {
then: cb => {
const status = url.indexOf('1') > -1 ? 200 : 500;
cb({
status: status ,
data: {
errors: ['this is a error test!']
}
});
}
};
}
- 网络请求url相同,没有额外参数,嗯,可以单独mock实现
import * as axios from 'axios';
jest.mock('axios');
......
test('Theme render correct', async () => {
axios.post.mockImplementation((url, data) => {
if (url == 'theme/default-theme') {
return {
then: cb => {
cb({
data: {
state: 0,
msg: '请求成功',
data: {
}
}
});
}
};
}
})
- document的方法报undefined?
const scrollIntoViewSpy = jest.fn();
jest.spyOn(document, 'getElementById').mockImplementation(() => {
return { scrollIntoView: scrollIntoViewSpy };
});
- mock moment?
Date.now = jest.fn().mockImplementation(() => {
return '2018-12-07T08:57:07.067Z';
});
- 解决Error: Not implemented: navigation https://github.com/jsdom/jsdom/issues/2112
delete window.location;
window.location = {};
- mock定时任务?
jest.useFakeTimers();
test('component render correct', async () => {
jest.runOnlyPendingTimers();
})
- 好吧 没有办法解决报错就解决报错本身
console.error = jest.fn().mockImplementation(() => {});