为什么在Jest测试中未调用此函数?

时间:2019-02-28 08:43:51

标签: javascript reactjs testing frontend jestjs

我正在尝试使用笑话反应测试一个功能。它可以在生产和开发环境中完美运行,但Jest表示没有调用。 因此,测试中的状态返回0个数据长度,而应为1个!

这是功能:

  addStory(story) {
const idToken = this.state.user.idToken
if (!idToken) return
const storyProps = {
  Title: story.title,
  Body: story.body,
  UserEntityKey: story.userEntityKey,
  AuthorName: this.state.user.displayName,
  AuthorPicture: this.state.user.photoURL
}

// Axios call should return Promise result for proper testing.
const promise = Axios.post(apiUrl, storyProps, { headers: { 'Authorization': idToken } })
promise.then(res => res.data)
promise.then(newStory => {
  newStory.data.AuthorName = this.state.user.displayName
  newStory.data.AuthorPicture = this.state.user.photoURL
  this.setState(({ data }) => {
    data.unshift(newStory.data)
    return { data: data, isAddStoryVisible: false }
  })
})
promise.catch((error) => {
  console.error(error)
})
return promise

};

这是测试:

let story = {
  Title: "title 1",
  body: "body 1",
  UserEntityKey: "userEntityKey",
  Key: "storyKey",
}

test('Story adds based on mocked backend response', async () => {
  MockAxios.post.mockImplementationOnce(() =>
    Promise.resolve(story)
  )

  const storyApp = shallow(<StoryApp />);

  // Test without idToken
  // Axios call should return Promise result.
  await storyApp.instance().addStory(story)
  expect(storyApp.state().data.length).toEqual(0)

  storyApp.setState((prev) => {
    prev.user = {
      idToken: "asdf",
      displayName: "Test name",
      photoURL: "Test photo"
    }
    return prev
  })

  // Test with idToken
  await storyApp.instance().addStory(story)
  expect(storyApp.state().data.length).toEqual(1)
})

最后是测试输出:

  ● Story adds based on mocked backend response

expect(received).toEqual(expected)

Expected value to equal:
  1
Received:
  0

  92 |   // Test with idToken
  93 |   await storyApp.instance().addStory(story)
> 94 |   expect(storyApp.state().data.length).toEqual(1)
     |                                        ^
  95 | })
  96 | 
  97 | test('Story deletes based on mocked backend response', async () => {

  at Object.toEqual (__tests__/App.test.js:94:40)
  at tryCatch (node_modules/regenerator-runtime/runtime.js:62:40)
  at Generator.invoke [as _invoke] (node_modules/regenerator-runtime/runtime.js:288:22)
  at Generator.prototype.(anonymous function) [as next] (node_modules/regenerator-runtime/runtime.js:114:21)
  at asyncGeneratorStep (__tests__/App.test.js:25:103)
  at _next (__tests__/App.test.js:27:194)

谢谢:-)

1 个答案:

答案 0 :(得分:1)

看起来只是一个错字。

为此更改MockAxios.post的嘲笑方式:

MockAxios.post.mockImplementationOnce(() =>
  Promise.resolve({ data: story })
)

...它应该可以工作。