我正在测试一个React类组件,它依赖于检索用户auth的服务。
async populateState() {
const result = await authService.getUserAuthenticationStatus();
const { user, isAuthenticated } = result;
this.setState({
isAuthenticated,
user
});
}因此,我想模拟getUserAuthenticationStatus的返回值,如下所示:
jest.mock('./components/api-authorization/AuthorizeService');
beforeAll(() => {
jest.spyOn(AuthService, 'getUserAuthenticationStatus').mockReturnValue(
Promise.resolve({
isAuthenticated: true,
user: {}
})
);
});这里的问题是,在运行我的测试时,方法总是返回undefined,而不是我在测试中设置的模拟值。如果我们快速查看导出的成员,我们可以看到类正在被实例化,然后导出。这会是问题吗?
const authService = new AuthorizeService();
export default authService;发布于 2022-08-18 19:41:07
我认为jest.mock在这里是不必要的。您可以简单地使用spyOn方法,因为您已经有了一个实例。
beforeAll(() => {
jest.spyOn(authService, 'getUserAuthenticationStatus')
// Returns promise no need to add manually
.mockResolvedValue({ isAuthenticated: true, user: {} });
});
// And make sure you clear the mocks in the end.
afterAll(() => jest.clearAllMocks());Note:你在监视authService,而不是AuthService
https://stackoverflow.com/questions/73408050
复制相似问题