【问题标题】:Mocking constructor callback模拟构造函数回调
【发布时间】:2019-01-08 00:08:05
【问题描述】:

我正在为使用react-native-sound 的AudioPlayer 类编写单元测试,因此我尝试使用__mocks__ 文件夹中的手动模拟来模拟react-native-sound。这是模拟类:

export default class Sound {
  _filename = null;
  _basePath = null;
  _duration = -1;
  _currentTime = 0;
  _volume = 1;
  _loaded = false;

  constructor(filename, basePath, callback) {
    this._filename = filename;
    this._basePath = basePath;
    this._duration = 500;
    this._loaded = true;

    callback();
  }

  static setCategory = (value, mixWithOthers) => {};
  static setMode = value => {};
  static setActive = value => {};

  isLoaded = () => { return this._loaded; };
  getDuration = () =>  { return this._duration; };
  getCurrentTime = callback => {
    callback(this._currentTime);
  };
  getVolume = () => { return this._volume; };
  setVolume = value => {
    this._volume = value;
  };
}

AudioPlayer 类有一个 load 方法,带有一个可选的音量参数,如下所示:

export default class AudioPlayer {
  loaded = false;
  load = (path: string, volume: number = 1) => {
    const that = this;
    return new Promise((resolve, reject) => {
      const sound = new Sound(path, "", error => {
        if (error) {
          reject(error);
        } else {
          sound.setVolume(volume); // <----- Fail here
          loaded = true;
          resolve();
        }
      });
    });
  };

而且,这是我在单元测试中尝试的内容:

jest.mock("react-native-sound");

describe("audio-player", () => {
  it("can load audio file", () => {
    expect.assertions(1);
    const audioPlayer = new AudioPlayer();
    const path = "sample_audio.mp3";
    return audioPlayer.load(path).then(() => {
      expect(audioPlayer.loaded).toEqual(true);
    });
  });
});

但是,这会失败并显示以下错误消息:

TypeError:无法读取未定义的属性“setVolume”

而且,这是因为尝试设置音量的代码在构造函数内部,并且无论出于何种原因,模拟类在构造函数内部仍然未定义。我该如何做?如何使用回调函数创建构造函数?

【问题讨论】:

    标签: unit-testing react-native mocking jestjs


    【解决方案1】:

    我想通了。我只是在 2000 毫秒超时内调用了构造函数内的回调函数:

    constructor(filename, basePath, callback) {
        this._filename = filename;
        this._basePath = basePath;
        this._duration = 500;
        this._loaded = true;
    
        setTimeout(() => {
            callback();
        }, 2000);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-24
      • 2013-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多