首页 > 解决方案 > 为 util 类编写笑话测试用例

问题描述

在 Vue 中,我有一个 util 类,我在其中抽象了 axios 调用和一些逻辑..

从'axios'导入Axios ..代码几乎看起来像这样

export default {
  getStudentNumber (name) {
    Axios.post('myurl', { studentName: name }).then({
      //some logic
      //return
    })
  }
}

这是从我的 Vue 类中调用的……我为 Vue 编写了开玩笑的测试用例,并在其中嘲笑了 Axios……但是有没有办法为这个服务类编写单独的测试用例?怎么写?因为我在这方面有很多逻辑......我在开玩笑

标签: vuejs2jestjs

解决方案


您可以像这样为您的服务编写测试:

import Axios from 'axios';
import myService from './myService';

jest.mock('axios');

describe('my service', () => {
  describe('getStudentNumber', () => {
    it('should call Axios.post with myurl and studentName', () => {
      myService.getStudentNumber('mock name');
      expect(Axios.post).toHaveBeenCalledWith('myurl', { studentName: 'mock name' })
    });

    describe('given a successful response', () => {
      beforeAll(() => {
        // setup mock for successful flow
        Axios.post.mockResolvedValue({ responseMock });
      });

      it('should do this', () => {
        const result = myService.getStudentNumber();
        // describe the expected result 
        expect(result).toEqual({ ...... });
      });
    });

    describe('given an error', () => {
      beforeAll(() => {
        // setup mock for non-successful flow
        Axios.post.mockRejectedValue(new Error('some mock error'));
      });

      it('should do that', () => {
        const result = myService.getStudentNumber();
        // describe the expected result 
        expect(result).toEqual({ ...... });
      });
    });
  });
});

推荐阅读