首页 > 解决方案 > 无法读取属性状态

问题描述

我尝试测试此操作:

const getGameList = function(context) {
  if(context.state.user.id){
    let request_body = {
        user_id : context.state.user.id
    }
    axios.post(`api/game_list_of_user`,request_body).then(response => {
      context.commit('UpdateGameList',response.data);
    }).catch(error => console.log(error));
  }
};

我的行动是获取特定用户的游戏列表。这个动作有:

我的测试:

import actions from '@/store/actions'
import state from '@/store/state'
import store from '@/store'
import axios from 'axios'

jest.mock('axios');

describe('getGameList', () => {
  test('Success: should return the game list of the user and update gameList in the store', () => {
    
    const state = { user: {id: 1} };
    const mockFunction = jest.fn();
    const response = {
      data: [ 
        { id:1, name:"game_name1" },
        { id:2, name:"game_name2" }
      ]
    };

    axios.post.mockResolvedValue(response);

    actions.getGameList({ mockFunction },{ state });

    //expect(mockFunction).toHaveBeenCalledTimes(1);
    //expect(mockFunction).toHaveBeenCalledWith('UpdateGameList',response.data);

  });

  test('Error: an error occurred', () => {
    const errorMessage = 'Error';
    axios.get.mockImplementationOnce(() =>
      Promise.reject(new Error(errorMessage))
    );
  });

});
  1. 我声明我的状态(使用我的用户 ID)。
  2. 我声明了我对请求的预期响应(游戏列表 = response.data)。
  3. 我使用 jest.fn() 来模拟这个函数。(我应该这样做吗?)

我收到了这个错误: 在此处输入图像描述

我想检查:

我该如何解决该错误?

编辑1:我的测试

jest.mock('axios');

describe('getGameList', () => {
  test('Success: should return the game list of the user and update gameList in the store', () => {
    
    const context = {
      state : { 
        user: {
          id: 1
        } 
      }
    };
    const mockFunction = jest.fn();
    const response = {
      data: [ 
        { id:1, name:"game_name1" },
        { id:2, name:"game_name2" }
      ]
    };

    axios.post.mockResolvedValue(response);

    actions.getGameList({ mockFunction, context });

    expect({ mockFunction, context }).toHaveBeenCalledTimes(1);
    expect(mockFunction).toHaveBeenCalledWith('UpdateGameList',response.data);

  });

  test('Error: an error occurred', () => {
    const errorMessage = 'Error';
    axios.get.mockImplementationOnce(() =>
      Promise.reject(new Error(errorMessage))
    );
  });
});

标签: vuejs2jestjsmockingstateaction

解决方案


这是我的解决方案:

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

});

推荐阅读