Mocha Mocking Js 实例函数
Mocha Mocking Js instance functions
使用 Mocha、Jsdom、enzyme 和 Expect 断言。
canPlayType
总是returns一个空字符串因为我不是运行浏览器中的测试。处理这个问题的最佳方法是什么?我会嘲笑它吗?如果是,我会如何嘲笑它?
规格文件:
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();
});
使用 Mocha、Jsdom、enzyme 和 Expect 断言。
canPlayType
总是returns一个空字符串因为我不是运行浏览器中的测试。处理这个问题的最佳方法是什么?我会嘲笑它吗?如果是,我会如何嘲笑它?
规格文件:
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();
});