【发布时间】:2021-12-31 06:24:12
【问题描述】:
我正在为我的 .ts 文件编写一次单元测试。我遇到问题并且无法找到解决方案的地方。希望有人能帮我解决它。
问题
在编写单元测试时。我无法测试 profile 的值。在调用名为 getProfile() 的方法之后。
文件设置
Profile.ts
import { getProfileAPI} from "./api";
class ProfileDetails implements IProfileDetails {
public profile: string = ''
constructor() {}
getProfile = async () => {
const { data } = await getProfileAPI();
if (data) {
this.profile = data
}
};
}
const profileDetail = new ProfileDetails();
export default profileDetail;
Profile.spec.ts
import Profile from './Profile';
describe('Profile', () => {
it('getProfile', async () => {
Profile.getProfile = jest.fn();
await Profile.getProfile();
expect(Profile.getProfile).toHaveBeenCalled();
});
});
所以我在这里面临的挑战是,我可以模拟 getProfile 方法。但我无法模拟在 getProfile 方法中调用的 getProfileAPI 函数。
如何模拟在模拟方法中调用的函数(或)是否有任何其他方法可以解决此问题。请帮忙。
提前致谢。
【问题讨论】:
-
您正在模拟您试图测试它是否被调用的
getProfile函数,这似乎有点奇怪。为什么不能模拟getProfileAPI函数?
标签: reactjs typescript unit-testing jestjs