【问题标题】:writing jest test cases for util classes为实用程序类编写笑话测试用例
【发布时间】:2019-05-13 04:32:58
【问题描述】:

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

import Axios from 'axios'..代码几乎是这样的

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

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

【问题讨论】:

  • “有没有办法为这个服务类编写单独的测试用例” 是的。这就是你想知道的全部吗?
  • 不..你怎么写的
  • 逐个测试。其余的取决于你的班级。您尝试了什么,什么没有奏效?

标签: vuejs2 jestjs


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2019-07-23
    • 2020-07-12
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-08
    相关资源
    最近更新 更多