简体   繁体   English

Mocha Mocking Js实例函数

[英]Mocha Mocking Js instance functions

Using Mocha, Jsdom, enzyme and Expect assertions. 使用Mocha,Jsdom,酶和Expect断言。

canPlayType always returns an empty string because I am not running the tests in a browser. 因为我不在浏览器中运行测试,所以canPlayType始终返回一个空字符串。 What's the best way to handle this? 处理此问题的最佳方法是什么? Do I mock it and if so how would I mock it? 我会嘲笑吗?如果是,我会怎么嘲笑呢?

spec file: 规格文件:

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

js file: js文件:

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

    return canPlay;
}

jsdom file: 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();
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM