【问题标题】:vue how to mock my external service classvue 如何模拟我的外部服务类
【发布时间】:2019-09-30 22:23:52
【问题描述】:

在我的 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.. 但我认为正确的方法是模拟 studentServices 而不是直接从组件模拟 axios ...

如何从 vue 组件测试中模拟 studentservices 并且在我的 vue 组件的测试用例中没有任何 axios?

【问题讨论】:

    标签: unit-testing vue.js vuejs2 jestjs


    【解决方案1】:

    Jest 文档描述类模拟 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();
        });
    
    });
    

    【讨论】:

      猜你喜欢
      • 2021-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-06
      • 1970-01-01
      • 2020-11-14
      • 1970-01-01
      相关资源
      最近更新 更多