了解如何模拟我的外部服务类

时间:2019-05-13 23:37:56

标签: unit-testing vue.js vuejs2 jestjs

在我的vue组件中,在已安装的组件中,我正在调用一个服务类,该类又调用axios调用..如下所示

import StudentService from '../utils/student.services'

export default {
  name: 'student-summary',

  mounted () {
    console.log('%c FeeMdoule-Data Recieved on Mount as %s', 'color: blue ;font-size : 12px', JSON.stringify(this.filingData))
    StudentService.getDetails().then(data => {
      this.sList = data
    })
  },

我现在已经编写了Vue组件的JEST测试用例,并且在vue组件测试用例中模拟了axios。 但是我认为正确的方法是模拟StudentService,而不是直接从组件中模拟axios ...

如何从vue组件测试中模拟学生服务,并且在我的vue组件的测试用例中没有任何axios?

1 个答案:

答案 0 :(得分:2)

玩笑文档描述类模拟here

StudentService.spec.js

import StudentService from '../utils/student.services'

jest.mock('../utils/student.services');

describe("StudentService", () => {
    let mockDetails = [{ studentId: 1 }]
    StudentService.getDetails = jest.fn().mockResolvedValue(mockDetails);

    afterEach(() => {
      // reset mock after each test
      StudentService.getDetails.mockReset();
    });

    it("should get details", () => {
      // ... mount your component
      expect(StudentService.getDetails).toHaveBeenCalled();
    });

});