测试从Vue JS应用程序中的API提取数据的代码

时间:2019-10-22 10:48:39

标签: javascript vuejs2 jestjs vue-test-utils

我正在尝试使用vue-test-utilsJest编写以下代码的单元测试,以了解是否已分配数据属性。

代码如下:

  created () {
    this.loadGridAndContent()
  },
  methods: {
    async loadGridAndContent () {
      let result = await AppService.loadDashboard(this.userDetails.psref).catch(err => console.log(err))
      this.dashBoardData = result.data[0]
      this.dashBoardDataClone = JSON.parse(JSON.stringify(this.dashBoardData))
    }
  }

AppService为

import Api from '@/services/api.service'

export default {
  async loadDashboard (psRef) {
    return Api().get('/user/' + psRef + '/dashboard')
      .catch(error => {
        console.log(error)
      })
  },
  async reorderDashboard (dashBoardOrderData) {
    return Api().put('/user/favourites/reorderdashboard', { NewOrder: dashBoardOrderData })
      .catch(error => {
        console.log(error)
      })
  }
}

模拟是

export default {
  loadDashboard: jest.fn(() => Promise.resolve([
    { db_name: 'Jobs', dxp_dashboardref: 1, dxp_hidden: 0, dxp_position: 1, dxp_ref: 926 },
    { db_name: 'Firms', dxp_dashboardref: 2, dxp_hidden: 0, dxp_position: 2, dxp_ref: 927 },
    { db_name: 'CRM', dxp_dashboardref: 5, dxp_hidden: 0, dxp_position: 3, dxp_ref: 987 }
  ]))
}

Api.js是:

import axios from 'axios'

export default () => {
  return axios.create({
    baseURL: ``,
    withCredentials: false,
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    }
  })
}

这是测试:

describe('DashBoard component tests', () => {
  let state
  let store
  let wrapper

  beforeEach(() => {
    state = {
      auth: {
        user: {
          auids: '',
          md_clock: 0,
          md_picture: '',
          ps_fname1: '',
          ps_surname: '',
          psname: 'Test Test',
          psref: 0
        }
      }
    }

    store = new Vuex.Store({
      state
    })

    wrapper = mount(Dashboard, {
      localVue,
      store
    })
  })

  afterEach(() => {
    wrapper.destroy()
  })

  it('it should assign dashBoardData to the result of AppService.loadDashboard', async () => {
    // expect.assertions(1)
    let dashBoardData = [
      { db_name: 'Jobs', dxp_dashboardref: 1, dxp_hidden: 0, dxp_position: 1, dxp_ref: 926 },
      { db_name: 'Firms', dxp_dashboardref: 2, dxp_hidden: 0, dxp_position: 2, dxp_ref: 927 },
      { db_name: 'CRM', dxp_dashboardref: 5, dxp_hidden: 0, dxp_position: 3, dxp_ref: 987 }
    ]
    let resp = { data: dashBoardData }

    console.log(loadDashboard.getMockImplementation)
    loadDashboard.mockResolvedValue(resp)
    //loadDashboard.mockImplementation(() => Promise.resolve(resp))

    await flushPromises()
    expect(wrapper.vm.dashBoardData).toEqual(dashBoardData)
  })
})

从本质上讲,我认为我是在嘲笑app.service的解析值,然后等待promises并断言data属性已分配。但是,我被抛出了

  

'TypeError:无法读取未定义的属性'0'

     

在VueComponent.loadGridAndContent
  (C:\ WebApp \ WebApp_Vue_Frontend \ src \ views \ dashboard \ Dashboard.vue:93:1)      在process._tickCallback(internal / process / next_tick.js:68:7)'

,我不确定为什么会这样。任何想法将不胜感激。

2 个答案:

答案 0 :(得分:0)

由于axios调用是GET请求,因此您应该查看文档:

  axios.get(url)
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .finally(function () {
    // always executed
  });

这就是说,您可以像这样使用回调(或Promises,更现代):

async loadDashboard (psRef, callback) {
    Api().get('/user/' + psRef + '/dashboard')
    .then(function(response){
        callback(response.data);
    })
    .catch(error => {
        console.log(error)
    })
}

并更改您的方法:

async loadGridAndContent () {
    await AppService.loadDashboard(this.userDetails.psref, this.callback).catch(err => console.log(err))
}

callback(data){
    this.dashBoardData = data[0]
    this.dashBoardDataClone = JSON.parse(JSON.stringify(this.dashBoardData))
}

总而言之,在使用响应之前,您要等待get()完成,这是通过上面的代码完成的。

希望这对您有所帮助。

我在这里很新,所以如果有错误,请告诉我。

答案 1 :(得分:0)

解决方案是实际正确模拟loadDashboard函数的解析值,例如

export default {
  loadDashboard: jest.fn(() => Promise.resolve({ data: [
    [
      { db_name: 'Jobs', dxp_dashboardref: 1, dxp_hidden: 0, dxp_position: 1, dxp_ref: 926 },
      { db_name: 'Firms', dxp_dashboardref: 2, dxp_hidden: 0, dxp_position: 2, dxp_ref: 927 },
      { db_name: 'CRM', dxp_dashboardref: 5, dxp_hidden: 0, dxp_position: 3, dxp_ref: 987 }
    ]
  ] }))
}