【发布时间】:2016-02-10 14:11:47
【问题描述】:
我尝试让我的 window 变量在我的导入类中可用。在它说的导入类中,该窗口未定义。
我使用 mocha 和 chai 来测试我的 javascript 代码。还有 babeljs 用于 es6 部分。
这是我的 test.js:
import { jsdom } from 'jsdom';
import { assert } from 'chai';
import sinon from 'sinon';
import Pixels from './../src/pixels.es6';
let document, window, pixels;
describe('Pixels', () => {
beforeEach(function () {
let el;
document = jsdom('<html><body></body></html>');
window = document.defaultView;
el = document.createElement('div');
el.setAttribute('data-flow-id', Date.now());
pixels = new Pixels(el);
});
describe('spawn()', function () {
beforeEach(function () {
window.dataLayer = {
push: sinon.spy()
};
pixels.spawn();
});
afterEach(function () {
window.dataLayer = {};
});
it('should push to dataLayer', function () {
assert.isTrue(window.dataLayer.push.called);
});
});
});
这是 window 不可用的导入类:
import { URL } from './config.es6';
import Parse from './parse.es6';
import fetch from 'safe-fetch';
export default class Pixels {
constructor (el) {
console.log(window);
this.el = el;
this.fetch = fetch || window.fetch;
}
spawn () {
this.fetch(URL, {
reportChildRequestId: false,
method: 'get'
}).then(resp => {
return resp.text();
}).then(html => {
// ... do stuff with html variable
});
}
}
摩卡电话是:mocha --require babel-core/register。
除了将window 变量传递到构造函数中之外,还有其他方法可以使window 变量在Pixels 中可用吗?
【问题讨论】:
标签: javascript mocha.js babeljs jsdom