在 React 模块中测试 SweetAlert2 的 preConfirm 挂钩
Testing preConfirm hook of SweetAlert2 in a React module
具有这样的 React 模块名称 Modal
:
import withReactContent from 'sweetalert2-react-content'
export const Modal = withReactContent(Swal)
const showModal = props => {
return Modal.fire({
...props,
showCloseButton: true
})
}
export default showModal
在另一个组件中用作用户操作的确认框
export const renderDeployModal = (deploymentId) => {
console.log(' - renderDeployModal - ')
Modal.fire({
type: 'question',
text: `Are you sure you wish to re-deploy this (${deploymentId})?`,
showCancelButton: true,
confirmButtonText: 'Deploy',
preConfirm: () => {
console.log(' - preConfirm - ')
return apiRequest(`/deployments/${deploymentId}/trigger`, {}, 'POST')
.then(response => {
return response.body
})
.catch(response => {
Modal.showValidationMessage(response.message)
})
},
allowOutsideClick: () => !Modal.isLoading()
}).then(result => {
if (result.value) {
notify('success', 'Your deployment has triggered.')
}
})
}
实现有效,但我遇到的问题是测试在 preConfirm
挂钩中执行的逻辑,因为我无法想出任何方法在我的测试中手动触发 Modal.clickConfirm()
并实际工作
import * as mockModal from '../../modal'
jest.mock('../../modal')
describe('renderDeployModal', () => {
it('fails to run a deploy without deploymentId argument', async () => {
const Modal = mockModal.Modal.mockImplementationOnce()
Modal.fire.mockImplementationOnce(() => Promise.resolve({ value: false }))
Modal.clickConfirm = jest.fn()
// Modal.clickConfirm.mockImplementation(() => Promise.resolve())
// const spy = jest.spyOn(mockModal.Modal, 'clickConfirm')
apiRequest.default = jest.fn().mockReturnValue(Promise.reject(new Error('foo')))
await renderDeployModal(null)
await Promise.resolve()
Modal.clickConfirm()
await Promise.resolve()
expect(Modal.fire).toHaveBeenCalled()
expect(Modal.clickConfirm).toHaveBeenCalled()
expect(apiRequest.default).toHaveBeenCalledWith(`/deployments/null/trigger`, {}, 'POST')
})
上述测试在 apiRequest
的最后预期失败。
console.log src/actions.js:111
- renderDeployModal -
FAIL src/actions.test.js
...
✕ fails to run a deploy without deploymentId argument (56ms)
● renderDeployModal › fails to run a deploy without deploymentId argument
expect(jest.fn()).toHaveBeenCalledWith(expected)
Expected mock function to have been called with:
["/deployments/null/trigger", {}, "POST"]
But it was not called.
148 | expect(Modal.fire).toHaveBeenCalled()
149 | expect(Modal.clickConfirm).toHaveBeenCalled()
> 150 | expect(apiRequest.default).toHaveBeenCalledWith(`/deployments/null/trigger`, {}, 'POST')
| ^
也显示了 console.log(' - renderDeployModal - ')
,但 console.log(' - preConfirm - ')
没有,表明 Modal.clickConfirm()
没有正确触发。
我在这里错过了什么?我没有想法(好或坏)去尝试。
每当你模拟一个模块时
jest.mock('../../modal')
它为模块对象对象的每个 属性 创建模拟函数而无需实现。
所以您将一个对象传递给 Modal.fire()
,它具有回调 preConfirm
,但没有任何东西应该调用它。因此,您可能应该将模拟实现更改为:
Modal.fire.mockImplementationOnce(({ preConfirm }) => {
preConfirm(); // <- execute the given callback
return Promise.resolve({ value: false })
})
然后期待它被调用
旁注: 顺便说一句,
没有意义
test('if I call a function it`s actually being called', () => {
Modal.clickConfirm() // <- execute a function within the test
expect(Modal.clickConfirm).toHaveBeenCalled() // and make sure it have been called few lines below
});
具有这样的 React 模块名称 Modal
:
import withReactContent from 'sweetalert2-react-content'
export const Modal = withReactContent(Swal)
const showModal = props => {
return Modal.fire({
...props,
showCloseButton: true
})
}
export default showModal
在另一个组件中用作用户操作的确认框
export const renderDeployModal = (deploymentId) => {
console.log(' - renderDeployModal - ')
Modal.fire({
type: 'question',
text: `Are you sure you wish to re-deploy this (${deploymentId})?`,
showCancelButton: true,
confirmButtonText: 'Deploy',
preConfirm: () => {
console.log(' - preConfirm - ')
return apiRequest(`/deployments/${deploymentId}/trigger`, {}, 'POST')
.then(response => {
return response.body
})
.catch(response => {
Modal.showValidationMessage(response.message)
})
},
allowOutsideClick: () => !Modal.isLoading()
}).then(result => {
if (result.value) {
notify('success', 'Your deployment has triggered.')
}
})
}
实现有效,但我遇到的问题是测试在 preConfirm
挂钩中执行的逻辑,因为我无法想出任何方法在我的测试中手动触发 Modal.clickConfirm()
并实际工作
import * as mockModal from '../../modal'
jest.mock('../../modal')
describe('renderDeployModal', () => {
it('fails to run a deploy without deploymentId argument', async () => {
const Modal = mockModal.Modal.mockImplementationOnce()
Modal.fire.mockImplementationOnce(() => Promise.resolve({ value: false }))
Modal.clickConfirm = jest.fn()
// Modal.clickConfirm.mockImplementation(() => Promise.resolve())
// const spy = jest.spyOn(mockModal.Modal, 'clickConfirm')
apiRequest.default = jest.fn().mockReturnValue(Promise.reject(new Error('foo')))
await renderDeployModal(null)
await Promise.resolve()
Modal.clickConfirm()
await Promise.resolve()
expect(Modal.fire).toHaveBeenCalled()
expect(Modal.clickConfirm).toHaveBeenCalled()
expect(apiRequest.default).toHaveBeenCalledWith(`/deployments/null/trigger`, {}, 'POST')
})
上述测试在 apiRequest
的最后预期失败。
console.log src/actions.js:111
- renderDeployModal -
FAIL src/actions.test.js
...
✕ fails to run a deploy without deploymentId argument (56ms)
● renderDeployModal › fails to run a deploy without deploymentId argument
expect(jest.fn()).toHaveBeenCalledWith(expected)
Expected mock function to have been called with:
["/deployments/null/trigger", {}, "POST"]
But it was not called.
148 | expect(Modal.fire).toHaveBeenCalled()
149 | expect(Modal.clickConfirm).toHaveBeenCalled()
> 150 | expect(apiRequest.default).toHaveBeenCalledWith(`/deployments/null/trigger`, {}, 'POST')
| ^
也显示了 console.log(' - renderDeployModal - ')
,但 console.log(' - preConfirm - ')
没有,表明 Modal.clickConfirm()
没有正确触发。
我在这里错过了什么?我没有想法(好或坏)去尝试。
每当你模拟一个模块时
jest.mock('../../modal')
它为模块对象对象的每个 属性 创建模拟函数而无需实现。
所以您将一个对象传递给 Modal.fire()
,它具有回调 preConfirm
,但没有任何东西应该调用它。因此,您可能应该将模拟实现更改为:
Modal.fire.mockImplementationOnce(({ preConfirm }) => {
preConfirm(); // <- execute the given callback
return Promise.resolve({ value: false })
})
然后期待它被调用
旁注: 顺便说一句,
没有意义test('if I call a function it`s actually being called', () => {
Modal.clickConfirm() // <- execute a function within the test
expect(Modal.clickConfirm).toHaveBeenCalled() // and make sure it have been called few lines below
});