代码之家  ›  专栏  ›  技术社区  ›  ataravati

模拟构造函数回调

  •  1
  • ataravati  · 技术社区  · 7 年前

    我正在为一个使用 react-native-sound ,所以我想嘲笑 react-native-sound 使用手动模拟 __mocks__ 文件夹。下面是模拟类:

    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类有一个带有卷的可选参数的加载方法,如下所示:

    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);
        });
      });
    });
    

    但是,此操作失败,并显示以下错误消息:

    类型错误:无法读取未定义的“setvolume”属性

    这是因为试图设置卷的代码在构造函数中,不管什么原因,模拟类在构造函数中仍然是未定义的。我该怎么做?如何使用回调函数生成构造函数?

    1 回复  |  直到 7 年前
        1
  •  0
  •   ataravati    7 年前

    我知道了。我只是在2000毫秒的超时时间内调用构造函数中的回调函数:

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