Jest throws TypeError: (0 , _module.myFunction) is not a function, testing exported functions (non default) with Jest
Jest throws TypeError: (0 , _module.myFunction) is not a function, testing exported functions (non default) with Jest
所以我正在使用 Jest、Typescript 和 Create-react-app
我有这个测试:
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' };
}
当我 运行 我的笑话测试它抛出:
TypeError: (0 , _http.defaultHeaders) is not a function
奇怪的是,包装在默认函数或 const 中的所有其他测试都有效。
有什么方法可以用 Jest 测试非默认导出函数吗?
更新:
- 还尝试将 defaultHeaders 转换为箭头函数,但没有帮助。
- 并尝试将导入更改为:
import * as http from './http'
仍然会引发相同的错误
更新答案
所以问题是,在 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 中删除模拟,那么我可以对其进行单元测试。
所以我正在使用 Jest、Typescript 和 Create-react-app
我有这个测试:
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' };
}
当我 运行 我的笑话测试它抛出:
TypeError: (0 , _http.defaultHeaders) is not a function
奇怪的是,包装在默认函数或 const 中的所有其他测试都有效。
有什么方法可以用 Jest 测试非默认导出函数吗?
更新:
- 还尝试将 defaultHeaders 转换为箭头函数,但没有帮助。
- 并尝试将导入更改为:
import * as http from './http'
仍然会引发相同的错误
更新答案
所以问题是,在 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 中删除模拟,那么我可以对其进行单元测试。