我怎么能模拟这个文件,不能覆盖setTimeout回调

时间:2018-03-20 08:53:09

标签: reactjs jest antd

需要在代码下面测试,如何模拟setTimeout回调

import { message } from 'antd';

const showMessage = ({ type = 'info', text }) => {
  message.destroy();
  setTimeout(() => {
     message[type](text); // this line can't covered
  }, 10);
};
export function error(text) {
  showMessage({ type: 'error', text });
}
export function info(text) {
  showMessage({ type: 'info', text });
}

1 个答案:

答案 0 :(得分:0)

您可以使用jest.runAllTimers()

jest.mock('antd');
const { message } = require('antd');

const { error } = require('../message');

describe('src/shared/utils/message', () => {
  describe('#error', () => {
    it('should call message.error', () => {
      error('dummy');
      jest.runAllTimers();

      expect(message.error).toBeCalledWith('dummy');
    }
  }
}