如何在开玩笑单元测试中处理.then和.catch

问题描述 投票:0回答:1

我正在使用与apollo客户端的反应,我正在尝试测试一个函数,它需要一个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个回答
0
投票

我认为你有两个可能的期​​望:

  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)
})

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

© www.soinside.com 2019 - 2024. All rights reserved.