首页 > 解决方案 > 为什么在调用后的开玩笑测试中无法读取未定义的属性'then'?

问题描述

我需要一些关于玩笑测试的帮助。我TypeError: Cannot read property 'then' of undefined在测试中遇到错误

Action Creators 中的 signIn 函数进行 POST 调用

import {SIGNING_IN, SIGNED_IN, SIGNING_FAILED, SIGNED_OUT} from "../actionTypes";
import {makePostCall} from "../../api/apiCalls";

export function signIn(data){
    return dispatch => {
        dispatch({type: SIGNING_IN});
        makePostCall('http://localhost:8000/api/v1/signin', data)
            .then(response => {
                const auth = {token: response.token, userId: response.id};
                localStorage.setItem('auth', JSON.stringify(auth));
                dispatch({type: SIGNED_IN, message: 'You signed in successfully.'});
            })
            .catch(error => {
                console.log('error: ', error);
                dispatch({type: SIGNING_FAILED, message: 'Email or Password incorrect. Please try again!'});
            });

    }
}

这是在上述调用中调用的 POST 调用函数

export function makePostCall(url, data){
    return axios({method: 'post', url, data})
        .then(response => response.data)
}

测试登录方法

jest.mock('../../../src/api/apiCalls');

describe('authenticationActionCreators', () => {
    describe('signIn', () => {

        let dispatch;
        beforeEach(() => {
            jest.clearAllMocks();
            const authResponse = getAuthResponse();
            makePostCall.mockReturnValue(Promise.resolve(authResponse));
            dispatch = jest.fn();
        });

        test('should make post call with correct URL and data', () => {
            const data = {email: 'user@user.com', password: 'password'};
            return signIn(data)(dispatch).then(() => {
                expect(makePostCall).toHaveBeenCalledWith('http://localhost:8000/api/v1/signin', {
                    email: 'user@user.com',
                    password: 'password'
                })
            })
        });

    });

每当我运行测试时,我都会在线出错return signIn(data)(dispatch).then(() => {

标签: javascriptreactjsreduxjestjs

解决方案


我做错了。我改变了它并且它有效

test('should make post call with correct URL and data', () => {
            const data = {email: 'user@user.com', password: 'password'};
            signIn(data)(dispatch);
            expect(makePostCall).toHaveBeenCalledWith('http://localhost:8000/api/v1/signin', {
                email: 'user@user.com',
                password: 'password'
            })
        });

推荐阅读