【问题标题】:How to handle .then and .catch in a jest unit test如何在开玩笑的单元测试中处理 .then 和 .catch
【发布时间】:2017-12-29 11:02:19
【问题描述】:

我正在对 apollo 客户端使用 react,并且我正在尝试测试一个需要 graphQL 突变的函数。由于这是函数的单元测试,我不想测试突变。 所以我需要模拟突变。这是我的功能:

changeContent (event) {
  const { content } = this.state
  const { id, language, changeMutation, t } = this.props

  changeMutation({
    variables: {
      id,
      content
    },
    refetchQueries: [{
      query: getContent,
      variables: {
        id,
        language
      }
    }]
  }).then(response => {
    this.setState({ content: response.data.changeContent.content })
  }).catch(error => {
    this.setState({ content })
    console.error(error)
    toast.error(t('error:content'))
  })
}

这就是我开始测试它的方式:

it('changeContent() should call mutation', () => {
  // SETUP
  const initial = 'Initial value'
  const new = 'New value'
  wrapper = shallow(<Content
    id='123'
    language='en'
    t={jest.fn()}
    changeMutation={jest.fn()}
  />)
  wrapper.setState({ content: initial })
  // EXECUTE
  wrapper.instance().changeContent()
  // VERIFY
  expect(wrapper.instance().state.content).toEqual(new)
})

但我不明白如何处理thencatch

【问题讨论】:

    标签: javascript unit-testing jestjs


    【解决方案1】:

    我认为您在这里有两个可能的期​​望:

    1. 当 changeMutation 的承诺得到解决时。
    2. 当来自 changeMutation 的承诺被拒绝时。

    所以你可以测试你的预期行为,为每个预期做两个测试,并正确模拟每个测试的 changeMutation 可能是这样的:

    承诺解决时:

        it('changeContent() should call mutation', async () => {
      // SETUP
      const initial = 'Initial value'
      const new = 'New value'
      wrapper = shallow(<Content
        id='123'
        language='en'
        t={jest.fn()}
        changeMutation={jest.fn(()=>Promose.resolve(yourExpectedResponse)}
      />)
      wrapper.setState({ content: initial })
      // EXECUTE
     await wrapper.instance().changeContent()
      // VERIFY
      expect(wrapper.instance().state.content).toEqual(new)
    })
    

    以及当 changeMutation 的承诺被拒绝时。

    it('changeContent() should call mutation', async () => {
      // SETUP
      const initial = 'Initial value'
      const new = 'New value'
      wrapper = shallow(<Content
        id='123'
        language='en'
        t={jest.fn()}
        changeMutation={jest.fn(()=>Promose.reject(yourExpectedError´)}
      />)
      wrapper.setState({ content: initial })
      // EXECUTE
      await wrapper.instance().changeContent()
      // VERIFY
      expect(wrapper.instance().state.content).toEqual(initial)
    })
    

    如果这是您的要求,请告诉我

    【讨论】:

    • Promise 可以同时定义resolvereject 吗?然后使用测试中需要的部分...
    • 你能给我举个例子吗?我想这就是我正在寻找的。​​span>
    猜你喜欢
    • 1970-01-01
    • 2020-10-23
    • 2015-12-30
    • 1970-01-01
    • 2017-10-01
    • 2018-09-10
    • 2019-07-21
    • 2022-01-13
    • 2019-07-04
    相关资源
    最近更新 更多