首页 > 解决方案 > How to spy on individual functions that are default exports

问题描述

I am trying to spy on a function that is used by the function I am actually testing, so the structure is a bit like this:

const trueOrFalse = (args) => {
  return true // or false;
}

export default TrueOrFalse;

and the function I want to import it into does

import trueOrFalse from './trueOrFalse';

const myFunc = () => {
  const successful = trueOrFalse();
  if (!successful) return;
  // Otherwise do something else
}

For my test now I need my trueOrFalse() to always return false for example. If this was exported differently I'd be able to use jest.spyOn like this:

  jest.spyOn(utils, 'trueOrFalse').mockImplementation(() => false);

But with this being a default export I can't do this, can I?

  jest.spyOn(???, 'trueOrFalse').mockImplementation(() => false);

How can I spy on or mock this dependent function?

标签: javascriptunit-testingjestjs

解决方案


可以在模块对象上监视或模拟函数:

import * as trueOrFalseMod from './trueOrFalse';

...

jest.spyOn(trueOrFalseMod, 'default');

这是因为 ES 导入总是在内部导入后引用对象属性。如果模块对象根据 ES 模块规范是只读的,这可能不起作用,这取决于特定的 Jest 设置。

否则需要模拟一个模块:

import trueOrFalse from './trueOrFalse';

jest.mock('./trueOrFalse');

这应该导致trueOrFalse成为可以根据测试更改实现的存根:

trueOrFalse.mockReturnValue(false);

推荐阅读