为了账号安全,请及时绑定邮箱和手机立即绑定

开玩笑测试解决拒绝回调

开玩笑测试解决拒绝回调

SMILET 2021-04-30 08:40:30
我有这个函数,它为api调用调用util函数。util函数根据api结果解析或拒绝。现在,我需要对具有以下结构的回调函数进行单元测试。`theClassMethod : () => {    return utilMethod().then(    result => { this.functionOne() //Test this function is called },     error => { this.functionTwo() //Test this function is called }    )}`util方法返回一个promise,如下所示:utilFunc = (data :string) :Promise<ResultData[]> => {    return new Promise(async (resolve, reject) => {        try{            resolve(data)        }catch{            reject(error)        }    }) }https://codesandbox.io/s/vjnwy1zw75?fontsize=14我试过的模拟util方法来解决/拒绝。调用类方法并执行断言。它不起作用,并且测试始终以假阳性通过。我花了很多时间寻找类似的问题。这里的大多数问题是要测试代码,例如:theClassMethod : () => { utilMethod.then().catch()}我要解决的问题是测试解决方案,然后在then块中拒绝回调then(function1, function2)。必须测试function1内部的代码块是否调用了某些预期的函数。
查看完整描述

1 回答

?
冉冉说

TA贡献1877条经验 获得超1个赞

您所描述的方法(模拟utilMethod解决/拒绝)是一种很好的方法。


这是一个简单的工作示例,可帮助您入门:


注:我实现了functionOne作为一个类的方法,并functionTwo作为一个实例属性,以显示如何在这两种类型的间谍功能:


util.js


export const utilMethod = async () => 'original';

code.js


import { utilMethod } from './util';


export class MyClass {

  functionOne() { }  // <= class method

  functionTwo = () => { }  // <= instance property

  theClassMethod() {

    return utilMethod().then(

      result => { this.functionOne() },

      error => { this.functionTwo() }

    );

  }

}

code.test.js


import { MyClass } from './code';

import * as util from './util';


test('theClassMethod', async () => {

  const mock = jest.spyOn(util, 'utilMethod');


  const instance = new MyClass();


  const functionOneSpy = jest.spyOn(MyClass.prototype, 'functionOne');  // <= class method

  const functionTwoSpy = jest.spyOn(instance, 'functionTwo');  // <= instance property


  mock.mockResolvedValue('mocked value');  // <= mock it to resolve

  await instance.theClassMethod();

  expect(functionOneSpy).toHaveBeenCalled();  // Success!


  mock.mockRejectedValue(new Error('something bad happened'));  // <= mock it to reject

  await instance.theClassMethod();

  expect(functionTwoSpy).toHaveBeenCalled();  // Success!

});


查看完整回答
反对 回复 2021-05-13
  • 1 回答
  • 0 关注
  • 140 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信