React项目Jest常见问题汇总

- 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公共组件的网络请求数据 否则会报
image

- E?(else 情况没有写,以为这样就完了?jest会认为你没有覆盖else,扣你覆盖率) I?(没有执行后面代码,???,需要查看下为什么没有执行到,是不是有别的报错了),看下面

image

image

- 网络请求 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(() => {});

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值