簡體   English   中英

如何檢查一個類方法是否只用 JEST 調用過一次

[英]How to check if a Class method has been called only once with JEST

問題:

我應該如何檢查Service.init()方法是否只被調用過一次?

錯誤
expect(received).toHaveBeenCalledTimes(expected)

    Matcher error: received value must be a mock or spy function

    Received has type:  object
    Received has value: {"constructor": [Function Statistics], "init": [Function init]}

      13 |     const Module3 = Service
      14 |
    > 15 |     expect(Service).toHaveBeenCalledTimes(1)
         |                     ^
      16 |   })
      17 |

代碼

index.spec.js:

  it('should initialized a class instance only once', async () => {
    const Service = require('./index')
    jest.mock('./index')

    const Module1 = Service
    const Module2 = Service
    const Module3 = Service

    expect(Service).toHaveBeenCalledTimes(1)
  })

基本上是一個類代碼:

class Statistics {
  constructor () {
    console.log('📊 Constructor')
    this.init()
  }

  async init () {
    // Wait 500ms
    console.log('📊 Initializing')
    await new Promise(resolve => setTimeout(resolve('ok'), 500))
    console.log('📊 Initialization complete')
  }
}

module.exports = new Statistics()

在檢查之前您沒有調用該函數。 文檔中的一個示例 - 使用.toHaveBeenCalledTimes確保模擬函數被調用的確切次數。

例如,假設您有一個drinkEach(drink, Array) 函數,該函數接受一個drink 函數並將其應用於傳遞的飲料數組。 您可能想要檢查飲料函數被調用的確切次數。 你可以用這個測試套件做到這一點:

test('drinkEach drinks each drink', () => {
  const drink = jest.fn();
  drinkEach(drink, ['lemon', 'octopus']); // calling the function and checking it
  expect(drink).toHaveBeenCalledTimes(2);
});

在您的測試規范中,創建實例足以調用 init:

  it('should initialized a class instance only once', async () => {
    const Service = require('./index');
    jest.mock('./index')

    const Module1 = Service
    const Module2 = Service
    const Module3 = Service
    const mockServiceInstance = Service.init();
    expect(Service).toHaveBeenCalledTimes(1)
  })

就我而言,我是在調用一個方法后監視它。

這不起作用:

it('should ...', () => {
  instance = new MyClass();
  expect(jest.spyOn(instance, 'methodname')).toBeCalled();
});

但這確實:

it('should ...', () => {
  const f = jest.spyOn(instance, 'methodname');
  instance = new MyClass();
  expect(f).toBeCalled();
});

暫無
暫無

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

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