1

我有一个提交表单的基本组件。这是声明表单提交的部分:

<form id="register" onSubmit={handleSubmit(onSubmit)}>

处理数据的函数是:

const onSubmit = async data => {
        
        const res = await axios.post("http://localhost", data)
             .then( (response) => {
                 console.log(response);
             })
             .catch(error => {
                 console.log(error);
             });
        
    }

在我的测试中,我声明了模拟,测试看起来像:

import axios from "axios";

jest.mock('axios', () => {
    post: () => Promise.resolve({data: []})
})

it('should save value when submitted', async () => {
            
            render(
                <Register />
            );

            ReactTestUtils.Simulate.change(field('email'), {
                target: { value: 'test@mail.com', name: 'email'}
            })

            ReactTestUtils.Simulate.change(field('first-name'), {
                target: { value: 'test', name: 'first-name'}
            })

            ReactTestUtils.Simulate.change(field('last-name'), {
                target: { value: 'test', name: 'last-name'}
            })

            ReactTestUtils.Simulate.change(field('password'), {
                target: { value: 'test', name: 'password'}
            })

            ReactTestUtils.Simulate.change(field('confirm-password'), {
                target: { value: 'test', name: 'confirm-password'}
            })


            ReactTestUtils.Simulate.submit(form('register'));


            expect(axios.post).toHaveBeenCalledTimes(1);
            

        });

注意: field并且form只是帮我获取任何字段和表单的助手。它们工作正常,它们已用于其他测试。

运行测试后,我收到以下错误:

RUNS test/Register.test.js node:internal/process/promises:245 triggerUncaughtException(err, true /* fromPromise */); ^

[UnhandledPromiseRejection:此错误源于在没有 catch 块的情况下抛出异步函数内部,或拒绝未使用 .catch() 处理的承诺。承诺被拒绝,原因是“TypeError: Cannot read property 'post' of undefined”。] {
code: 'ERR_UNHANDLED_REJECTION' }

这里发生了什么?我没有处理catch声明中的拒绝吗?

4

0 回答 0