摩卡模拟 Js 实例函数



使用Mocha,Jsdom,enzyme和Expect断言。

canPlayType总是返回一个空字符串,因为我没有在浏览器中运行测试。处理这个问题的最佳方法是什么?我是否嘲笑它,如果是,我将如何嘲笑它?

规范文件:

it('should be able to play media',() => {
    expect(canPlayMedia()).toBe(true);
});

js 文件:

const canPlayMedia = () => {
    const mediaElement = document.createElement('audio');
    // canPlayType is always empty string
    const canPlay = mediaElement.canPlayType('audio/mpeg');
    return canPlay;
}

JSDOM 文件:

// setup the simplest document possible
const doc = jsdom.jsdom('<!doctype html><html><body></body></html>');
// get the window object out of the document
const win = doc.defaultView;
// set globals for mocha that make access to document and window feel
// natural in the test environment
global.document = doc;
global.window = win;
// from mocha-jsdom https://github.com/rstacruz/mocha-jsdom/blob/master/index.js#L80
const propagateToGlobal = (window) => {
  Object.keys(window).forEach((key) => {
    if (Object.prototype.hasOwnProperty.call(window, key) && !(key in global)) {
      global[key] = window[key];
    }
  });
};
global.document.webkitExitFullscreen = () => null;
// take all properties of the window object and also attach it to the
// mocha global object
propagateToGlobal(win);
it('should be able to play audio',() => {
    const audio = document.createElement('audio');
    expect.spyOn(document, 'createElement').andReturn(audio);
    expect.spyOn(audio, 'canPlayType').andReturn(true);
    expect(canPlayMedia()).toBe(true);
    document.createElement.restore();
});

最新更新