为什么mockAxios.post.mockImplementationOnce没有返回任何数据

时间:2018-05-10 05:59:42

标签: jestjs axios-mock-adapter

为什么mockAxios.post.mockImplementationOnce没有返回任何数据?我想看看错误。

  it('should show errors when submitting returns a 422 response', () => {
    mockAxios.post.mockImplementationOnce(() =>
      Promise.resolve({
        data: { errors: ['Name is required.', 'Email is required.'] },
        status: 422,
      })
    )

    addStudentForm()
      .find('button.open-modal')
      .simulate('click')
    addStudentForm()
      .find('button.submit')
      .simulate('click')

    expect(addStudentForm().instance().state.showModal).toBe(true)
    console.log(addStudentForm().instance().state)
  })

这是我的状态,因为它在console.log中。

{ showModal: true,
 name: '',
 username: '' }

在前端,event.response.data中的回复确实向我显示了我想要看到的内容errors :["Name is required.", "Email is required."],但我似乎无法嘲笑它。

如果您需要查看完整背景信息:https://github.com/freeCodeCamp/classroom-mode/blob/mock-axio/client/src/test/AddStudentForm.test.js

当我等待

时有趣
await addStudentForm()
  .find('button.submit')
  .simulate('click') 

expect(addStudentForm()。instance()。state.showModal).toBe(true)返回false。

1 个答案:

答案 0 :(得分:1)

您似乎错过了done(),这就是为什么测试早先完成然后模拟数据返回的原因:

it('should show errors when submitting returns a 422 response', done // < --HERE ->
=> {
    mockAxios.post.mockImplementationOnce(() => {
      Promise.resolve({
        data: { errors: ['Name is required.', 'Email is required.'] },
        status: 422,
      });

    addStudentForm()
      .find('button.open-modal')
      .simulate('click')
    addStudentForm()
      .find('button.submit')
      .simulate('click')

    expect(addStudentForm().instance().state.showModal).toBe(true)
    console.log(addStudentForm().instance().state);

      done(); // <- HERE ->
    })


  })