我需要使用 Jest 模拟 React 应用程序(使用 create-react-app 创建)中的导入函数。我尝试执行文档和其他线程中显示的操作(例如此处:Jest – How to mock non-default exports from modules?),但它不起作用。目前我的项目是这样的:
调用 getOne.js
import {getOne} from "../../Services/articleService";
export const a = async function () {
return getOne("article1");
};
articleService.js
export const getOne = async function (id) {
return;
};
testss.test.js
import {ArticleTypes} from "../../Data/articleTypes";
import {getOne} from "../../Services/articleService";
import {a} from "./calls getOne";
jest.mock("../../Services/articleService", () => {
return {
getOne: jest.fn().mockImplementation(async (id) => {
const articles = {
article1: {
title: "Some valid title",
description: "Some valid description",
type: /*ArticleTypes.General*/"a"
}
};
return Promise.resolve(articles[id]);
})
};
});
const mockedGetOne = async (id) => {
const articles = {
article1: {
title: "Some valid title",
description: "Some valid description",
type: ArticleTypes.General
}
};
return Promise.resolve(articles[id]);
};
beforeAll(() => {
getOne.mockImplementation(mockedGetOne);
});
test("calls getOne", async () => {
const res = await a();
expect(getOne).toHaveBeenCalled();
expect(res).not.toBeUndefined();
});
我目前在 jest.mock 中使用的工厂函数的模拟中注释掉了 ArticleTypes。我需要使用它们,但我不能在工厂函数中使用导入的文件。我只是想测试模拟是否可以在那里工作,但它在任何地方都不起作用。
为什么我不能模拟导入?我错过了什么吗?我需要一些我不知道的额外配置吗?