Estoy probando un componente de clase React que se basa en un servicio para recuperar la autenticación del usuario.
async populateState() { const result = await authService.getUserAuthenticationStatus(); const { user, isAuthenticated } = result; this.setState({ isAuthenticated, user }); } Entonces, me gustaría simular el valor de retorno de getUserAuthenticationStatus así:
jest.mock('./components/api-authorization/AuthorizeService'); beforeAll(() => { jest.spyOn(AuthService, 'getUserAuthenticationStatus').mockReturnValue( Promise.resolve({ isAuthenticated: true, user: {} }) ); }); El problema aquí es que cuando ejecuto mis pruebas, el método sigue devolviendo undefined en lugar del valor simulado que configuré en mi prueba. Si echamos un vistazo rápido al miembro exportado, podemos ver que la clase se crea una instancia y luego se exporta. ¿Podría ser éste el problema?
const authService = new AuthorizeService(); export default authService;Creo que jest.mock es innecesario aquí. Simplemente puede espiar el método ya que ya tiene una instancia.
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()); Nota : está espiando el servicio de authService , no el Servicio de AuthService