首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在React模块中测试SweetAlert2的SweetAlert2钩子

在React模块中测试SweetAlert2的SweetAlert2钩子
EN

Stack Overflow用户
提问于 2019-10-16 08:33:04
回答 1查看 1.3K关注 0票数 1

具有这样的React模块名Modal

代码语言:javascript
复制
import withReactContent from 'sweetalert2-react-content'

export const Modal = withReactContent(Swal)
const showModal = props => {
  return Modal.fire({
    ...props,
    showCloseButton: true
  })
}

export default showModal

在另一个组件中用作用户操作的确认框。

代码语言:javascript
复制
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()并实际工作的任何方法。

代码语言:javascript
复制
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的预期中失败。

代码语言:javascript
复制
  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()没有正确触发。

我在这里错过了什么?我没有什么想法(好的或坏的)去尝试。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-10-16 15:17:03

每当你像你一样嘲笑一个模块时

代码语言:javascript
复制
jest.mock('../../modal')

它在没有实现的情况下为模块对象的每个属性创建模拟函数。

因此,您要将一个对象传递给Modal.fire(),后者具有回调preConfirm,但是没有什么可以调用它。因此,您可能应该将模拟实现更改为如下所示:

代码语言:javascript
复制
Modal.fire.mockImplementationOnce(({ preConfirm }) => {
  preConfirm(); // <- execute the given callback
  return Promise.resolve({ value: false })
})

然后期望它被调用

附带注意:,顺便说一句,没有意义

代码语言:javascript
复制
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
});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58409018

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档