【问题标题】:Axios.post mock function is not called with Jest, VueJSAxios.post 模拟函数不使用 Jest 调用,VueJS
【发布时间】:2021-03-17 22:43:29
【问题描述】:

我想测试我的行为。

  • 我的操作有 1 个 AXIOS 请求和 1 个突变。
  • 我用 jest.mock(“axios” ...) 模拟了我的 axios。我返回一个 Promise。
  • 我使用 mockResolvedValue() 方法定义了一个模拟值。

但是当我测试我的 axios.post 是否使用 toHaveBeenCalledTimes(1) 方法调用时,Jest 告诉我 0 次。

我的测试:

我的行动:

我的错误:

有人知道为什么我的 axios.post 没有被调用吗?

【问题讨论】:

  • 请张贴代码而不是图片。见stackoverflow.com/help/how-to-ask。你没有做任何可以调用它的事情,所以它没有被调用。而且您仅使用其他断言而不是实际单元来测试您自己的测试。
  • 对不起,我不会再发布任何代码的图像了。谢谢你让我知道。我找到了解决方案,我发布解决方案。
  • 很高兴您将其整理出来,欢迎在 SO 上自行回答

标签: vue.js axios jestjs mocking


【解决方案1】:

这是解决方案:

    import actions from '@/store/actions'
    import mutations from '@/store/mutations'
    import state from '@/store/state'
    import store from '@/store'
    import axios from 'axios'
    
    let url = ''
    let body = {}
    
    jest.mock("axios", () => ({
      post: jest.fn((_url, _body) => { 
        return new Promise((resolve) => {
          url = _url
          body = _body
          resolve(true)
        })
      })
    }))
    
    //https://medium.com/techfides/a-beginner-friendly-guide-to-unit-testing-the-vue-js-application-28fc049d0c78
    //https://www.robinwieruch.de/axios-jest
    //https://lmiller1990.github.io/vue-testing-handbook/vuex-actions.html#testing-actions
    describe('getGameList', () => {
      test('Success: should return the game list of the user and update gameList in the store', async () => {
        const context= {
          state: {
            user: {
              id:1
            }
          },
          commit: jest.fn()
        }
        const response = {
          data: [ 
            { id:1, name:"game_name1" },
            { id:2, name:"game_name2" }
          ]
        };
    
        axios.post.mockResolvedValue(response) //OR axios.post.mockImplementationOnce(() => Promise.resolve(response));
        await actions.getGameList(context)
        expect(axios.post).toHaveBeenCalledWith("api/game_list_of_user",{"user_id":1});
        expect(axios.post).toHaveBeenCalledTimes(1)
        expect(context.commit).toHaveBeenCalledWith("UpdateGameList", response.data)
    
      });
    
      test('Error: an error occurred', () => {
        const errorMessage = 'Error';
        axios.post.mockImplementationOnce(() =>
          Promise.reject(new Error(errorMessage))
        );
      });
    
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 2019-07-22
    • 2019-05-29
    • 2019-10-31
    • 2022-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多