Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 是否可以在节点中为没有catch块的promise编写jest单元测试?_Node.js_Reactjs_Unit Testing_Jestjs_Redux Saga - Fatal编程技术网

Node.js 是否可以在节点中为没有catch块的promise编写jest单元测试?

Node.js 是否可以在节点中为没有catch块的promise编写jest单元测试?,node.js,reactjs,unit-testing,jestjs,redux-saga,Node.js,Reactjs,Unit Testing,Jestjs,Redux Saga,有什么问题 我正在尝试编写一个带有用户登录名的基本react django样板文件。我正在使用react saga处理登录流 我有一个调用登录函数的传奇,它ping服务器并获取令牌。这个故事处理了所有的错误处理。如果该调用失败,则会成功返回错误以作出反应并显示给用户。它工作正常 我正在尝试为登录函数编写一个单元测试。我认为节点正在捕获我的错误:unhandledPromisejectionWarning:unhandledPromisejection。此错误源于在没有catch块的情况下抛出异步

有什么问题

我正在尝试编写一个带有用户登录名的基本react django样板文件。我正在使用
react saga
处理登录流

我有一个调用登录函数的传奇,它ping服务器并获取令牌。这个故事处理了所有的错误处理。如果该调用失败,则会成功返回错误以作出反应并显示给用户。它工作正常

我正在尝试为登录函数编写一个单元测试。我认为节点正在捕获我的错误:
unhandledPromisejectionWarning:unhandledPromisejection。此错误源于在没有catch块的情况下抛出异步函数内部,或者拒绝未使用.catch()处理的承诺。

我猜因为saga在现实中捕捉到了它,node并没有抛出那个错误

这是否意味着我不能单元测试登录函数是否会抛出未捕获的错误

我应该不去测试这个吗

代码

这是调用服务器的函数

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

    });
});

你可以测试一下
toThrow
方法用于捕获抛出的错误,但promise拒绝错误,因此需要使用不同的API。捕获错误
。拒绝.toThrow()您还应
等待expect块完成,从而导致:

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
    });
});
注:这在中有很好的记录。

()=>
应该省略,因为
登录
实际上不会抛出。