簡體   English   中英

開玩笑:嘲笑條件函數調用

[英]Jest: mocking conditional function calls

我正在嘗試編寫一個測試,以確保在適當的情況下,使用特定的消息調用特定的函數(在這種情況下為哨兵函數)。 但是,當我編寫此測試時,它失敗了,並且收到以下消息。 如何正確模擬handleError.test.jscaptureMessage函數,以確保使用"this is an error message."正確調用了該"this is an error message." handleError.js字符串? 謝謝!

錯誤信息:

錯誤:expect(jest.fn())[。not] .toHaveBeenCalledWith()

jest.fn()值必須是模擬函數或間諜。 收到:函數:[Function captureMessage]

handleError.js:

import {captureMessage} from '@sentry/browser';

const handleError = (error) => {
  if (error.name === "ApiError") {
    captureMessage('this is an error message.');
  }
};

export default handleError;

handleError.test.js:

import {captureMessage} from '@sentry/browser';
import handleError from '../handleError';

class ApiError extends Error {
  constructor() {
    super();
    this.name = 'ApiError';
  }
}

test('When an ApiError is returned with no action type, sentry is notified', () => {
  const sampleError = new ApiError();
  handleError(sampleError);
  expect(captureMessage).toHaveBeenCalledWith('this is an error message.');
});

如@balzee所述,您實際上必須監視要進行斷言的方法。 這導致Jest用特殊的間諜函數替換該方法,該函數跟蹤被調用的參數,被調用的次數等等。

您還應該為該函數提供一個模擬實現,這樣,在運行單元測試時實際上就不會調出Sentry了。

最后,在監視方法時,首先傳遞該方法所在的對象,然后將該方法的名稱作為字符串傳遞。 然后,Jest用一個間諜函數替換該對象上的該屬性,如果沒有給出模擬實現,它將調用原始函數。

如果不引用函數所在的對象,則只需將本地函數變量指向的對象從原始/實函數更改為開玩笑的間諜函數即可。 那不會改變您正在測試的代碼調用的功能,因此測試將失敗。

因此,最終測試應為:

handleError.test.js:

import * as sentry from '@sentry/browser'; // CHANGED
import handleError from '../handleError';

class ApiError extends Error {
  constructor() {
    super();
    this.name = 'ApiError';
  }
}

// added this to remove any spies/mocks after the test
afterEach(() => {
  jest.restoreAllMocks();
});

test('When an ApiError is returned with no action type, sentry is notified', () => {
  const sampleError = new ApiError();
  // added next line
  jest.spyOn(sentry, 'captureMessage').mockImplementation(() => {});
  handleError(sampleError);
  // note the use of `sentry.captureMessage`, which is now a jest spy fn
  expect(sentry.captureMessage).toHaveBeenCalledWith('this is an error message.');
});

暫無
暫無

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

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