Jest 抛出 TypeError: (0 , _module.myFunction) 不是函数,使用 Jest 测试导出函数(非默认)

Com*_*ode 12 typescript jestjs create-react-app

所以我使用 Jest、Typescript 和 Create-react-app

我有这个测试:

import { defaultHeaders } from './http';

describe('http tests', () => {
  test('defaultHeaders()', () => {
    const headers = defaultHeaders(undefined);
    expect(headers).toEqual({ foo: 2 });
  });
});
Run Code Online (Sandbox Code Playgroud)

该代码位于文件中的同一子目录中http.ts,如下所示:

export function defaultHeaders(headers?: FetchHeaders): FetchHeaders {
  return { 'Content-Type': 'application/json' };
}
Run Code Online (Sandbox Code Playgroud)

当我运行笑话测试时,它会抛出:

TypeError: (0 , _http.defaultHeaders) is not a function
Run Code Online (Sandbox Code Playgroud)

奇怪的是,包装在默认函数或 const 中的所有其他测试都可以工作。

有没有办法用 Jest 测试非默认导出函数?

更新:

  • 还尝试将 defaultHeaders 转换为箭头函数,但这没有帮助。
  • 并尝试将导入更改为:import * as http from './http'这仍然会引发相同的错误

Com*_*ode 15

更新答案

所以问题是,src/setupTest.ts我包含了模块的模拟,但没有我试图测试的功能,因此它是未定义的。

// mock our fetch wrapper to avoid doing http calls in tests
jest.mock('utilities/http/http', () => ({
  // NO defaultHeaders() function mocked that was the problem 
  getRequest: function () {
    return {
      json: {},
      status: 200,
    };
  },
  postRequest: function () {
    return {
      json: {},
      status: 200,
    };
  },
  request: function () {
    return {
      json: {},
      status: 200,
    };
  },
}));
Run Code Online (Sandbox Code Playgroud)

如果我从 setupTest.ts 中删除模拟,那么我可以对其进行单元测试。