簡體   English   中英

JS/Jest: mocking a class 檢查方法是否被調用

[英]JS/Jest: mocking a class to check if method called

我正在嘗試在我的主 js 文件中測試播放器的加載。 它只是創建了一個 IVSPlayer class 的新實例,然后對其調用init()
主.js

const ivsPlayer = new IVSPlayer({
  id: VIDEO_PLAYER_ID,
  config: VIDEO_JS_CONFIG,
  ivsTech: win.registerIVSTech,
});
ivsPlayer.init();

player = ivsPlayer.player;

我正在嘗試模擬下面的實現

MAIN.test.js

import IVSPlayer from './ivs-player';

it('should load the  player', async () => {
  const mockInit = () => jest.fn();

  jest.mock('./ivs-player', () => {
    return {
      init: mockInit,
    };
  });

  await createPlayers();

  expect(?????).toHaveBeenCalled();
});

自從我嘲笑了 ivs-player 后,我該放什么來期待聽

我認為您的 mocking 是錯誤的。 試試這個(模擬原型)

it('should load the  player', async () => {
  IVSPlayer.prototype.init = jest.fn().mockImplementation(() => {
    return {
      init: jest.fn(),
    };
  });

  // execute code that causes the init function to run

  expect(IVSPlayer.prototype.init).toHaveBeenCalled();
});

或者,你可以試試這個

import { IVSPlayer } from './ivs-player';

jest.mock('./ivs-player'); // Automatic mock of the file

it('should load the  player', async () => {
  // execute code that causes the init function to run

  const mockInit = IVSPlayer.mock.instances[0].init;

  expect(mockInit).toHaveBeenCalled();
});

您可以在此處閱讀有關 class 模擬的更多信息。

暫無
暫無

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

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