简体   繁体   中英

Jest Issue with mocking api call and checking error

I am using jest and trying to test an asynchronous login request. I am able to check that the call has resolved and is successful. I would also like to test the case that the call wasn't successful.

I have been following the docs from here .

I understand I am not doing the reject correctly, but if I move the jest.mock('.utils/api', () => {... into the test block it doesn't work, it needs to be outside. Can anyone advise the correct way to do this?

See my code below:

import React from 'react';
import { render, fireEvent } from 'react-testing-library';
import Login from './index';
import { login as mockLogin } from './api';

let mockData = {
    token: '12345'
};

let errorData = {
   message: 'Your username/password is incorrect'
};

jest.mock('.utils/api', () => {
    return {
        jsonRequest: jest.fn(() => new Promise((resolve, reject) => {
            resolve(mockData,);
            // I am not doing this correctly.
            reject(errorData);
        })),
    };
});


describe('<Login />', () => {   

    it('returns a sessionId if successful and error if not', () => {

        const { getByLabelText, getByText } = render(<Login />);
        const loginButton = getByText(/login/i);
        fireEvent.click(loginButton);
        expect(mockLogin).toBeCalledTimes(1);
        expect(mockLogin).toHaveBeenCalledWith('/login', {
            data: {
                password: 'test',
                username: 'test',
            },
            method: 'POST',
        });

        expect(mockLogin()).resolves.toBe(mockData);
        expect(mockLogin()).rejects(mockData);
    });
});

What you need to test here is the behavour of your component when the API rejects the request for some reason.

Assume this scenario:

Lets say the reason for rejection is that the "Entered password is not correct" . Then you need to make sure that the Login component will show an error message to the DOM where the user can see it and re-enter his password

To test this you need to make a check inside the mocked API, something like:

jsonRequest: jest.fn((formDataSubmittedFromComponent) => new Promise((resolve, reject) => {
    // Notice that the mocked function will recieve the same arguments that the real function recieves from the Login component
    // so you can check on these arguments here
   if (formDataSubmittedFromComponent.password !== mockData.password) {
     reject('Entered password is not correct') // << this is an error that your component will get and should handle it
   }
  resolve();

})),

After that you should test how did your component handle the reject

For example, you could test whether or not it displayed an error message to the DOM:

const errorMessageNode = getByTestId('error-message');
expect(errorMessageNode).toBeTruthy()

Edit: before you fire the login event you should make sure that the form is populated with the mocked data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM