简体   繁体   English

嘲笑api调用和检查错误的开玩笑问题

[英]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? 我了解我没有正确执行reject ,但是如果我将jest.mock('.utils/api', () => {...移到测试块中,它将无法正常工作,它必须在外部。任何人都可以建议这样做的正确方法吗?

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. 当API由于某种原因拒绝请求时,您需要在此处测试的是组件的行为。

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 然后,您需要确保Login组件将向DOM显示一条错误消息,用户可以在其中看到并重新输入密码

To test this you need to make a check inside the mocked API, something like: 要对此进行测试,您需要在模拟的API中进行检查,例如:

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: 例如,您可以测试它是否向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 编辑:触发登录事件之前,您应确保使用模拟数据填充表单

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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