javascript - 如何使用 jest 模拟导出带有类变量的类的模块

标签 javascript react-native jestjs

我有一个通过以下方式使用 react-native-sound 的模块:

const Sound = require('react-native-sound');
...
const something = Sound.DOCUMENT;
const someOtherThing = new Sound();

如何模拟这样的模块?

最佳答案

我使用手动模拟(在 __mocks__ 文件夹中)模拟了react-native-sound,如下所示:

const isFakeFilename = filename => /^blah.*/.test(filename);

const mockFunctions = {
  play: jest.fn(cb => {
    console.log('*** Playing sound! ***');
    cb && cb(isFakeFilename(this.filename) ? false : true);
  }),
  setCategory: jest.fn(),
  getDuration: jest.fn(() => 100),
  getNumberOfChannels: jest.fn(() => 8)
};

const Sound = function(filename, blah2, cb) {
  this.play = mockFunctions.play.bind(this);
  this.filename = filename;
  const savedFilename = filename;
  setTimeout(() => {
    if (isFakeFilename(savedFilename)) {
      cb && cb(new Error('File does not exist! (mocked condition)'));
    } else {
      cb && cb();
    }
  });
};

Sound.prototype.play = mockFunctions.play.bind(Sound.prototype);
Sound.prototype.getDuration = mockFunctions.getDuration;
Sound.prototype.getNumberOfChannels = mockFunctions.getNumberOfChannels;

Sound.setCategory = mockFunctions.setCategory;

export default Sound;
export { mockFunctions };

请注意如何直接添加声音导入上的方法 (Sound.setCategory),以及如何在类实例上添加方法 (playgetDuration) > 等)是使用原型(prototype)添加的。

使用 mockFunctions 导出可能会增加一点复杂性。我用它来检查对模拟函数的调用,方法是将其单独导入到测试文件中,如

import { mockFunctions } from 'react-native-sound';
// ...
expect(mockFunctions.play).toHaveBeenCalled();

关于javascript - 如何使用 jest 模拟导出带有类变量的类的模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51027294/

相关文章:

javascript - 如何在 Typescript 和 Angular 2 中使用 "@input set"检索数据?

javascript - 调试未定义的 Jest 快照

reactjs - 使用 jest 和 react-testing-library 测试对象的属性时出错

javascript - 我想使用 css 选择器单击一个元素并在新的浏览器窗口中打开它,然后使用 Jquery 或 JS 将它发送到现有浏览器窗口后面

javascript - 在使用 jQuery 打开时,将更多选项添加到选择下拉列表中

javascript - CodeMirror - 更新选择

security - 如何在 React Native 应用程序中保持客户端 JSON Web token 的安全?

javascript - 动态设置 Apollo 客户端 header 不起作用

javascript - React native 导航在 promise 后不呈现

Reactjs - Jest 快照测试嵌套 redux "connected"组件