UnhandledPromiseRejectionWarning: шутка - PullRequest
       73

UnhandledPromiseRejectionWarning: шутка

0 голосов
/ 01 августа 2020

Когда я пытался запустить приведенный ниже код для тестирования моего запроса ax ios с помощью шутки, я получаю следующее предупреждение, хотя мои тесты проходят.

fetchNoteHandler = async () => {    
        const headers = {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + this.props.idToken
        }
        return axios.get(`${ROOT_URL}/notes/${this.state.noteId}`, {
            headers: headers,
            cancelToken: this.source.token
        })
        .then(response => {
            this.setState({
                noteId: response.data["noteId"],
                heading: response.data["noteHeading"],
                note: response.data["noteBody"],
                lastUpdated: response.data["lastUpdated"],
                fetchingNow: false
            });
        })
        .catch((error) => {
            if (!axios.isCancel(error)) {
                this.setState({
                    fetchingNow: false,
                    error: "Failed to fetch note"
                });
            }
        });
    }

Функция fetchNoteHandler ( ) вызывается из componentDidUpdate ().

it('should ', (done) => {
    let fetchSuccess;
    const axiosSpy = jest.spyOn(axios, 'get').mockImplementation(() => {
        const thenFn = jest.fn().mockImplementationOnce((onfulfilled) => {
            fetchSuccess = onfulfilled;
        })
        return { then: thenFn }
    })
    
    const wrapper = setup({ auth: authUpdatedState }, { location: { search: { id: randomNoteId }}})
    expect(axiosSpy).toBeCalledTimes(1);
    fetchSuccess(sampleResponse);
    done();
});
(node:69127) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'catch' of undefined
(Use `node --trace-warnings ...` to show where the warning was created)
(node:69127) 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(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:69127) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Как я могу обрабатывать необработанные обещания в этом случае?

1 Ответ

0 голосов
/ 02 августа 2020

Это потому, что вы не обнаруживаете ошибок в своем тесте и не возвращаете Promise. Попробуйте так:

const axiosSpy = jest.spyOn(axios, 'get').mockImplementationOnce(() => 
    Promise.resolve(yourMockData)
);
...