代码之家  ›  专栏  ›  技术社区  ›  David Schumann Axnyff

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

  •  0
  • David Schumann Axnyff  · 技术社区  · 8 年前

    我有一个模块 react-native-sound 在以下方面:

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

    我如何模拟这样的模块?

    1 回复  |  直到 8 年前
        1
  •  1
  •   stone    8 年前

    我使用手动模拟(在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 )和类实例上的方法。( play 我是说, getDuration 等)使用原型添加。

    有一点增加的复杂性,您可能不需要使用 mockFunctions 出口。我使用它来检查对模拟函数的调用,方法是将其单独导入测试文件,如下所示

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