我对React应用程序中的错误处理的测试不起作用,我不确定为什么。我正在测试的代码在main.js中,当我通过让api发回错误响应来在浏览器中测试功能时,它可以正常工作。我还检查了使用console.log调用进行测试时,被测代码是否到达正确的“ case 404”代码块,因此问题似乎出在displayErrorModal的模拟上。
//main.js (code to be tested)
import React from 'react'
import { SOMETHING_WENT_WRONG, FORBIDDEN, NOT_FOUND, NO_RESPONSE,
REQUEST_FAILED } from './util/error-message-types'
import displayErrorModal from './util/display-error-modal'
import { get } from 'axios'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import App from './app'
const patientId = window.requestParameters.patient_id
get('/api/v1/patients/' + patientId + '/views/multi-episode-summary',
{
patientId
}).then( //do some stuff
).then( // do some stuff
).catch((error) => {
if (error.response) { //response status code not 2xx
switch (error.response.status) {
case 403:
displayErrorModal('Error', FORBIDDEN)
break;
case 404:
displayErrorModal('Error', NOT_FOUND)
break;
case 500:
default:
displayErrorModal('Error', SOMETHING_WENT_WRONG)
break;
}
} else if (error.request) {//no response received
displayErrorModal('Error', NO_RESPONSE)
} else {//error in making request
displayErrorModal('Error', REQUEST_FAILED)
}
})
// display-error-modal.js within util folder
import ErrorModal from '../../../error-modal'
import React from 'react'
import { render } from 'react-dom'
export default (headerText, bodyText) => {
return render(
<ErrorModal
header={headerText}
body={bodyText}
/>,
document.getElementById('multiple-episode-view-app')
)
}
// main.test.js within a __tests__ folder
import React from 'react'
import axios from 'axios'
import displayErrorModal from '../util/display-error-modal'
import { SOMETHING_WENT_WRONG, FORBIDDEN, NOT_FOUND, NO_RESPONSE,
REQUEST_FAILED } from '../util/error-message-types'
const { it, expect } = global
jest.mock('axios')
jest.mock('../util/display-error-modal')
describe('Multi Episode Summary App', () => {
it('displays error modal for patient not found', () => {
window.requestParameters = { patient_id: 100019 }
const errorResponse = new Error('Patient not found.')
errorResponse.response = { status: 404 }
axios.get.mockRejectedValue(errorResponse)
require('../main')
expect(displayErrorModal).toHaveBeenCalledWith('Error', NOT_FOUND)
})
})
运行测试时,它失败,并显示消息“预期已使用以下方法调用了模拟函数:...但未调用。”