代码之家  ›  专栏  ›  技术社区  ›  Joseph Chambers

为什么mockAxios没有。邮递mockImplementationOnce返回任何数据

  •  1
  • Joseph Chambers  · 技术社区  · 6 年前

    为什么mockAxios没有。邮递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)
      })
    

    这是我的状态,因为它在控制台中。日志

    { 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()。实例()。状态showModal)。toBe(true)返回false。

    1 回复  |  直到 6 年前
        1
  •  2
  •   Alejandro    6 年前

    你好像错过了 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 ->
        })
    
    
      })