我有一个调用 API 的函数,它会根据第一次 API 调用返回的内容进行第二次 API 调用。但是第一个 API 总是返回 undefined
getTotalCount = async () => {
const { showCountCallBack, showCount } = this.props;
try {
const response = await showCount();
const count = isEmpty(response.result);
if (count) {
console.log(" success");
} else {
showCountCallBack({ ...this.state });
}
} catch (e) {
console.log("error");
}
};
describe("component", () => {
let shallowComponent;
let shallowComponentInstance;
const showCountMock = jest.fn(() => Promise.resolve({ result: [] }));
const showCountCallBackMock = jest.fn(() => Promise.resolve({ result: [] }));
beforeEach(() => {
showCountMock.mockReset();
shallowComponent = shallowWithTheme(
<Component
showCount={showCountMock}
showCountCallBack={showCountCallBackMock}
/>
);
shallowComponentInstance = shallowComponent.instance();
});
it("viewMapping", () => {
shallowComponentInstance.getTotalCount();
expect(showCountMock).toHaveBeenCalledTimes(1);
expect(showCountCallBackMock).toHaveBeenCalledTimes(1);
});
});
最佳答案
经过几个小时的挣扎。我找到了原因。是 mockReset
导致了这个问题。
它也重置了返回值。所以我只是从代码中删除了 mockReset
。最好在这里使用 mockClear
关于jestjs - Promise.resolve 从 Jest 模拟函数返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56472512/