Reactjs 如何模拟模块内的对象/函数
我在模拟模块内的函数时遇到问题。(不确定这是否可行 所以我有一个名为myActions.ts的模块Reactjs 如何模拟模块内的对象/函数,reactjs,jestjs,Reactjs,Jestjs,我在模拟模块内的函数时遇到问题。(不确定这是否可行 所以我有一个名为myActions.ts的模块 import * as Config from "../utils/Config"; const _config = Config.getConfig(); export const requestLoadDataA = (postLoadAction: Function = undefined) => { return async function (dispatch, getS
import * as Config from "../utils/Config";
const _config = Config.getConfig();
export const requestLoadDataA = (postLoadAction: Function = undefined) => {
return async function (dispatch, getState) {
const client = { url: `${_config.ApiUrl}getDataA` };
...
}
}
这个模块包含一个Config.getConfig(),这就是我想要模拟的
配置模块如下所示:
export const getConfig = () => {
const app = document.getElementById("react-app");
if (app) {
const config = app.dataset.configuration;
return JSON.parse(config) as IConfiguration;
} else {
return undefined;
}
};
这是我到目前为止的玩笑测试,但它不起作用:
describe("DATA_A Action Creator (Sync): Tests", () => {
afterEach(fetchMock.restore);
it("REQUEST and SUCCESS actions on successful loadData()", () => {
const dataA: any = require("../../__mockData__/dataA.json");
fetchMock.mock("/getDataA", {
status: 200,
body: dataA
});
const _config = { };
const spy = jest.spyOn(Config, "getConfig");
spy.mockReturnValue(_config);
const store = mockStore({
dataA: {
hasLoadedEntities: false,
isLoadingEntities: false
}
});
return store.dispatch(aActions.requestLoadDataA())
.then(() => {
const expectedActions = store.getActions();
expect(expectedActions.length).toEqual(2);
expect(expectedActions).toContainEqual({ type: ACTION_TYPES.LOAD_A_REQUESTED });
expect(expectedActions).toContainEqual({ type: ACTION_TYPES.LOAD_A_SUCCESS, data: resultData });
});
});
}
我得到一个“无法读取未定义的属性'apirl'。
如何模拟_config.apirl对象?我不确定是否理解您的意思 您可以像这样模拟默认导入
import * as Config from "../utils/Config";
jest.mock("../utils/Config", () => ({
getConfig: () => ({ ApiUrl: 'yourMockApiUrl' })
}));
我在requestLoadDataA()之前将您的代码添加到jest测试中,但它不起作用,_config仍然未定义。有什么想法吗?您可以尝试一下路径是否正确,如果我更改它,我会收到消息“找不到模块…”。。。。“。mockImplementation具有相同的结果。我认为这是因为Config模块不是一个typescript类,在中只有一些导出的函数,然后在测试文件中,我将所有内容作为Config导入,我不知道如何正确实现此场景下的mock。我在想,我如何确保在我调用requestLoadDataA()之前,在myActions.ts中调用了“const _config=config.getConfig();”?哦,我刚做了。我应该在myActions.ts中模拟_配置。你的解决方案帮助了我。