javascript - 如何使用 Jest 测试同一个类中的方法调用?

标签 javascript jestjs

我正在尝试测试类内部的函数调用,以确保它们被调用,但我似乎不知道如何使用 Jest 来做到这一点。

自动模拟不起作用,使用模块工厂参数调用 jest.mock 也不起作用。

这是有问题的类,我想测试调用 play() 是否会调用 playSoundFile()。

class SoundPlayer {
  constructor() {
    this.foo = 'bar';
  }

  playSoundFile(fileName) {
    console.log('Playing sound file ' + fileName);
  }

  play() {
    this.playSoundFile('song.mp3');
  }
}

module.exports = SoundPlayer;

这是测试文件:

const SoundPlayer = require('../sound-player');
jest.mock('../sound-player');

it('test', () => {
  const soundPlayerConsumer = new SoundPlayer();

  const coolSoundFileName = 'song.mp3';
  soundPlayerConsumer.play();

  const mockPlaySoundFile = SoundPlayer.mock.instances[0].playSoundFile;
  expect(mockPlaySoundFile.mock.calls[0][0]).toEqual(coolSoundFileName);
});

mockPlaySoundFile.mock.calls 为空,因此出错。

最佳答案

我建议你不要模拟任何内部方法。相反,您可以模拟任何外部依赖项并调用应该是公共(public)的方法。然后,您针对公共(public)(应该在外部调用)方法返回的内容运行断言,并检查模拟(模拟的外部依赖项)是否被调用。

在这个特定的例子中只有 console.log :

console.log = jest.fn();
const soundPlayerConsumer = new SoundPlayer();
soundPlayerConsumer.play();
expect(console.log).toHaveBeenCalledTimes(1);
expect(console.log).toHaveBeenCalledWith('Playing sound file song.mp3');

在更真实的场景中,可能需要您模拟 document甚至使用 jsdom mock <audio /> HTML 元素。但方法是一样的。

关于javascript - 如何使用 Jest 测试同一个类中的方法调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56134988/

相关文章:

javascript - 如何用 Jest 测试一系列数字?

javascript - 使用 javascript 创建 reamore 按钮

javascript - 如何在此处使用 $watch 以便在指令 USING ui-router 之前触发 API

php - 需要一种使用 javascript 重复轮询文件的简单方法

reactjs - 开 Jest : Cannot find module 'react' , 和其他 node_modules

javascript - Promise.allSettled 不是 Jest 测试中的函数,如何模拟?

javascript - Web App 在 Webview 内部运行并像 native App 一样安装

javascript - [Electron][OSX] 始终显示托盘图标

node.js - 如何在 JEST 测试用例中检查全局获取的响应

angular - HttpTestingController ExpectOne匹配URL错误