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

Typescript Jest抛出TypeError:(0,_module.myFunction)不是函数,使用Jest测试导出的函数(非默认),typescript,jestjs,create-react-app,Typescript,Jestjs,Create React App,所以我在使用Jest、Typescript和CreateReact应用程序 我有这个测试: import { defaultHeaders } from './http'; describe('http tests', () => { test('defaultHeaders()', () => { const headers = defaultHeaders(undefined); expect(headers).toEqual({ foo: 2 });

所以我在使用Jest、Typescript和CreateReact应用程序

我有这个测试:

import { defaultHeaders } from './http';

describe('http tests', () => {
  test('defaultHeaders()', () => {
    const headers = defaultHeaders(undefined);
    expect(headers).toEqual({ foo: 2 });
  });
});
代码位于文件
http.ts
的同一子目录中,如下所示:

export function defaultHeaders(headers?: FetchHeaders): FetchHeaders {
  return { 'Content-Type': 'application/json' };
}
当我运行jest测试时,它抛出:

TypeError: (0 , _http.defaultHeaders) is not a function
奇怪的是,包装在默认函数或常量中的所有其他测试都可以工作

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

更新:
  • 还尝试将defaultHeaders转换为arrow函数,但没有任何帮助
  • 并尝试将导入更改为:
    import*作为http从“/http”
    中删除,但仍然会引发相同的错误

    • 您没有正确导入DefaultHeader。在这里,您可以做两件事:-

    • 将导入行从“./http/http”更改为import{defaultHeaders}
    • 或者,如果您想让这段代码正常工作,您需要将http.ts重命名为index.ts, 然后它可以直接从http目录引用defaultHeaders
    • 默认情况下,导入语句引用目录中的索引文件。

      使用应答更新 因此问题在于,在
      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,
          };
        },
      }));
      

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

      除非您在同一文件中重新定义了
      defaultHeaders
      export,否则这种情况不会发生。导出显示为未定义的一种常见情况是循环依赖,但您发布的代码并不表明这一点。请提供可以重现此问题的选项。调试通过
      import*作为http从“/http”
      导入的内容,以及
      从“/http”
      导入http,这仅在您这边是可能的。还可以尝试
      const{defaultHeaders}=require('./http')
      const{defaultHeaders}=require('./http')。默认值
      。这些尝试涵盖了TS模块互操作不正确的可能性。