为util类编写开玩笑的测试用例

时间:2019-05-13 04:32:58

标签: vuejs2 jestjs

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

从'axios'导入Axios。代码几乎像这样

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

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

1 个答案:

答案 0 :(得分:0)

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

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({ ...... });
      });
    });
  });
});