[Vuejs]-Axios.post mock function is not called with Jest, VueJS

3👍

This is the solution:

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

👤DamTan

Leave a comment