Jest Mock 返回未定义而不是数据

Bat*_*man 8 javascript jestjs

我正在尝试模拟一个函数,但不确定我在这里做错了什么。我有这个功能“getGroups”

获取组:

export const getGroups = async () => {
  try {
    const groupApiUrl = getDashboardPath(GROUPS_TAB_INDEX);
    const data = await fetch(groupApiUrl, { cache: 'force-cache' });
    const userData = await data.json();
    return userData;
  } catch (error) {
    throw Error(error);
  }
};
Run Code Online (Sandbox Code Playgroud)

___mocks___/getGroups.js:

export default async () => {
  return {
    groups: [
      { id: 1, name: 'Data1' },
      { id: 2, name: 'Data2' }
    ]
  };
};
Run Code Online (Sandbox Code Playgroud)

getGroups.test.js:

jest.mock('./getGroups.js');
// eslint-disable-next-line import/first
import { getGroups } from './getGroups';

const fakeRespose = {
  groups: [
    { id: 1, name: 'Data1' },
    { id: 2, name: 'Data2' }
  ]
};

describe('getGroups', () => {
  it('returns data', async () => {
    const data = await getGroups();
    console.log('DATA', data);  <---- UNDEFINED?
    expect(data).toBeDefined();
    expect(data).toMatchObject(fakeRespose);
  });

  it('handles error', async () => {
    // const data = await getGroups();
    await getGroups().toThrow('Failed');
  });
});
Run Code Online (Sandbox Code Playgroud)

Bar*_*zev -1

以下是来自 Jest Docs 的 Mock 示例。

jest.mock('../moduleName', () => {
  return jest.fn(() => 42);
});

// This runs the function specified as second argument to `jest.mock`.
const moduleName = require('../moduleName');
moduleName(); // Will return '42';
Run Code Online (Sandbox Code Playgroud)

在您的情况下data是未定义的,因为您实际上没有为该函数提供模拟实现,或者模拟没有工作,并且您仍在调用原始函数。

示例参考:https://jestjs.io/docs/en/jest-object#jestmockmodulename-factory-options

但是,在您的简单情况下,您也可以使用间谍来解决此问题,或者jest.spyOnjest.fn()。以下是您想要实现的目标的两种解决方案。您可以在此处查看代码并运行它:https://repl.it/repls/FairUnsungMice

评论后更新:

__mocks__/ 手动模拟是通过在紧邻模块的子目录中编写模块来定义的。例如,要模拟 models 目录中名为 user 的模块,请创建一个名为 user.js 的文件并将其放入该models/__mocks__目录中。请注意,该 __mocks__文件夹区分大小写,因此__MOCKS__在某些系统上命名该目录会中断。

仔细检查您设置的导出的命名、目录结构和类型 - 它们应该匹配。另外,值得检查一下:https://github.com/facebook/jest/issues/6127 - 看起来像是笑话的一个开放问题。如果您需要解决方案,请考虑使用我提到的不同方法。

参考: https: //jestjs.io/docs/en/manual-mocks