簡體   English   中英

開玩笑測試解決拒絕回調

[英]Jest test the resolve reject callback

我有此函數,它為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

我試過的

  1. 模擬util方法來解決/拒絕。 調用類方法並執行斷言。 它不起作用,並且測試始終以假陽性通過。

我花了很多時間尋找類似的問題。 這里的大多數問題是要測試代碼,例如:

theClassMethod : () => { utilMethod.then().catch()}

我正在嘗試解決的問題是測試解決方案,然后在then塊then(function1, function2)拒絕回調。 必須測試function1內部的代碼塊是否調用了某些預期的函數。

您正在描述的方法( 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!
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM