Можно ли написать шутный юнит-тест в узле для обещания без блока catch? - PullRequest
1 голос
/ 06 апреля 2019

В чем проблема

Я пытаюсь написать базовый шаблон реакции django с логином пользователя.Я обрабатываю поток входа в систему с помощью react-saga.

У меня есть сага, которая вызывает функцию входа в систему, которая пингует сервер и получает токен.Сага обрабатывает все ошибки обработки.Если этот вызов не удается, ошибка успешно возвращается, чтобы реагировать и показывается пользователю.Он работает правильно.

Я пытаюсь написать модульный тест для функции входа в систему.Я думаю, что нод улавливает мою ошибку: UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch().

Я думаю, потому что сага ловит ее в реальности, нода не выдает эту ошибку.

Означает ли это, что я не могу выполнить юнит-тестирование?функция входа должна выдавать неперехваченную ошибку?

Должен ли я просто не потрудиться проверить это?

Код

Эта функция вызывает сервер.

 # Auth login function

login(email, password) {
    // If user is already logged in return true.
    if (auth.loggedIn()) return Promise.resolve(true);
    const credentials = btoa(`${email}:${password}`);
    // Request to login
    return axios({
        method: "post",
        url: `${SERVER_URL}/api/v1/accounts/login/`,
        headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
            Authorization: `Basic ${credentials}`
        }
    }).then(response => {
        // Save token to local storage
        if (response.data.token) {
            localStorage.auth_token = response.data.token;
        } else {
            // To Do-- throw error if server fails to return one
        }
        return Promise.resolve(true);
    });
}

Тогда это сага, которая обрабатывает логику.

export function* authorize({
    email,
    password,
    isRegistering,
    firstName,
    lastName
}) {
    // We send an action that tells Redux we're sending a request
    yield put({ type: SENDING_REQUEST, sending: true });

    // We then try to register or log in the user, depending on the request
    try {
        let response;

        // For either log in or registering, we call the proper function in the `auth`
        // module, which is asynchronous. Because we're using generators, we can work
        // as if it's synchronous because we pause execution until the call is done
        // with `yield`!
        if (isRegistering) {
            response = yield call(
                register,
                email,
                password,
                firstName,
                lastName
            );
        } else {
            response = yield call(login, email, password);
        }

        return response;
    } catch (error) {
        // If we get an error we send Redux the appropriate action and return
        yield put({
            type: REQUEST_ERROR,
            error: error.response.data,
            sending: false
        });

        return false;
    } finally {
        // When done, we tell Redux we're not in the middle of a request any more
        yield put({ type: SENDING_REQUEST, sending: false });
    }
}

Тогда это мой юнит-тест:

describe("login function", () => {
    let mock;

    beforeEach(() => {
        mock = new MockAdapter(axios);
        localStorage.clear();
    });

    afterEach(() => {
        // We need to clear mocks
        // and remove tokens from local storage to prevent
        // us from staying logged in
        mock.restore();
    });

    test("Check that exception thrown on server error", () => {
        // Mock loggedin function to throw error
        mock.onPost().reply(500);
        Test that error is uncaught.
        expect(() => {
            auth.login("test@example.com", "pass").then(value => {
                console.log(value);
            });
        }).toThrow();

    });
});

1 Ответ

1 голос
/ 07 апреля 2019

Вы можете проверить это. toThrow метод используется для отлова сгенерированных ошибок, но обещание отклоняет ошибки, поэтому требует использования другого API. Чтобы поймать вашу ошибку .rejects.toThrow();, вам также нужно await, чтобы ожидаемый блок завершился, что приведет к:

describe("login function", () => {
    let mock;

    beforeEach(() => {
        mock = new MockAdapter(axios);
        localStorage.clear();
    });

    afterEach(() => {
        // We need to clear mocks
        // and remove tokens from local storage to prevent
        // us from staying logged in
        mock.restore();
    });

    test("Check that exception thrown on server error", async () => {
        // Mock loggedin function to throw error
        mock.onPost().reply(500);
        Test that error is uncaught.
        await expect(() => auth.login("test@example.com", "pass")).rejects.toThrow(); // add an error message to check for correct error
    });
});

PS. Это хорошо задокументировано в jest API документах .

...