【问题标题】:How can I test custom callbacks passed to Axios API using jest + enzyme如何使用 jest + 酶测试传递给 Axios API 的自定义回调
【发布时间】:2020-06-28 16:41:34
【问题描述】:

在我的反应应用程序中,我使用 axios 完成了一个异步 api 调用。并且该 api 调用确实接受自定义回调。

我可以使用 Jest + Enzyme 测试 axios api 调用。但无法测试自定义回调方法。

注意:我已经模拟了我的 axios 模块。

src/mocks/axios.js

export default {
    get: jest.fn(() => Promise.resolve({ data: {} })),
    post: jest.fn(() => Promise.resolve({ data: {} }))
}

auth.api.js

import Axios from 'axios';
import { AUTH_SERVER_URL } from './../../settings';
import { setAuthToken } from '../actions/auth/auth.action';

export const saveUsers = (user, dispatch) => {
    const URL = `${AUTH_SERVER_URL}/auth/register`;
    Axios.post(URL, user)
        .then(response => {
            const { data } = response;
            const token = {
                accessToken: data.access_token,
            };
            return token;
        })
        .then(token => dispatch(setAuthToken(token)))
        .catch(error => {
            if (error.response) {
                console.error(error.response.data.message);
            }
        })
}

这是我的测试代码。

spec.js

import mockAxios from 'axios';
import { AUTH_SERVER_URL } from './../../settings';
import { saveUsers } from './auth.api';
import { setAuthToken } from '../actions/auth/auth.action';

describe('Authentication API', () => {
    it('saveUsers', () => {

        const user = { x: 'test' }
        const dispatch = jest.fn(); // need to test this dispatch function gets called or not
        const response = {
            data: {
                access_token: 'access_token',
            }
        };
        const expectedToken = {
            accessToken: 'access_token',
        };
        mockAxios.post.mockImplementationOnce(() => Promise.resolve(response));

        saveUsers(user, dispatch);

        const url = `${AUTH_SERVER_URL}/auth/register`;
        expect(mockAxios.post).toHaveBeenCalledTimes(1);
        expect(mockAxios.post).toHaveBeenCalledWith(url, user);
        console.log(dispatch.mock.calls);

        expect(dispatch).toHaveBeenCalledTimes(1); // failed
        expect(dispatch).toHaveBeenCalledWith(setAuthToken(expectedToken)); // failed

    });
})

请帮帮我

【问题讨论】:

    标签: reactjs jestjs axios enzyme


    【解决方案1】:

    尝试安装这个包flush-promises

    然后将其导入您的测试文件中

    import flushPromises from 'flush-promises';
    

    并在你的断言之前添加它。

    ...
    
    await flushPromises();
    
    expect(dispatch).toHaveBeenCalledTimes(1);
    expect(dispatch).toHaveBeenCalledWith(setAuthToken(expectedToken)); 
    

    并在此处添加 async

    it('saveUsers', async () => {
    

    但我不确定它是否会有所帮助。

    【讨论】:

    • 有什么方法可以在不添加任何额外包的情况下实现这一点?
    【解决方案2】:

    感谢 @Jakub Janik 的回答。

    Bellow 是我不使用 flush-promise 包的答案。但它使用了 flush-promise 背后的概念。

    import mockAxios from 'axios';
    import { AUTH_SERVER_URL } from './../../settings';
    import { saveUsers } from './auth.api';
    import { setAuthToken } from '../actions/auth/auth.action';
    
    // A helper function can turn that into a promise itself so you don't need to deal with the done callback.
    const flushPromises = () => new Promise(resolve => setImmediate(resolve));
    
    describe('Authentication API', () => {
        it('saveUsers', async () => {
    
            const user = { x: 'test' }
            const dispatch = jest.fn(); // need to test this dispatch function gets called or not
            const response = {
                data: {
                    access_token: 'access_token',
                }
            };
            const expectedToken = {
                accessToken: 'access_token',
            };
            mockAxios.post.mockImplementationOnce(() => Promise.resolve(response));
    
            saveUsers(user, dispatch);
    
            const url = `${AUTH_SERVER_URL}/auth/register`;
            expect(mockAxios.post).toHaveBeenCalledTimes(1);
            expect(mockAxios.post).toHaveBeenCalledWith(url, user);
    
            await flushPromises(); // Magic happens here
    
            expect(dispatch).toHaveBeenCalledTimes(1);
            expect(dispatch).toHaveBeenCalledWith(setAuthToken(expectedToken));
    
        });
    })
    

    【讨论】:

      猜你喜欢
      • 2018-09-28
      • 2019-04-21
      • 2019-11-15
      • 2021-06-04
      • 2018-03-25
      • 1970-01-01
      • 2020-01-18
      • 2020-07-15
      • 2019-04-24
      相关资源
      最近更新 更多