Как проверить пользовательские обратные вызовы, передаваемые в Ax ios API, используя jest + энзим - PullRequest
1 голос
/ 17 марта 2020

В моем приложении «Реакция» у меня есть вызов API asyn c, выполненный с помощью топора ios. И этот вызов API принимает пользовательский обратный вызов.

Я могу проверить вызов API ax ios, используя Jest + Enzyme. Но не в состоянии протестировать пользовательский метод обратного вызова.

Примечание: я издевался над модулем своего топора ios.

src / mocks / топор ios. 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);
            }
        })
}

А вот мой тестовый код.

spe c. 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

    });
})

Пожалуйста, помогите мне в этом

Ответы [ 2 ]

2 голосов
/ 17 марта 2020

Попробуйте установить этот пакет flu sh -promises .

Затем импортируйте его в свой тестовый файл

import flushPromises from 'flush-promises';

и добавьте его перед утверждениями.

...

await flushPromises();

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

А здесь добавьте asyn c.

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

Но я не уверен, поможет ли это.

1 голос
/ 17 марта 2020

Спасибо @ Jakub Janik за его ответ.

Ниже приведен мой ответ без использования пакета обещания flu sh. Но он использует концепцию, лежащую в основе гриппа sh -обещание .

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));

    });
})
...