因此,我正在尝试使用 Headless Chromes + Puppeteer + Mocha + Sinon 对我的 Google Analytics 调用进行自动测试,但无法读取数据层值以供 Sinon 进行监视。
这就是我到目前为止所拥有的。但是窗口总是未定义的。test 是一个代理传递 puppeteer 调用到内部浏览器的类。
const { test } = require('../browser');
const sinon = require('sinon');
const dataLayerName = 'dataLayer';
const assert = sinon.assert;
describe('Tests Analytics', () => {
let spy;
it('find home analytics', test(async (browser, opts) => {
const page = await browser.newPage();
await page.goto(`${opts.appUrl}`);
spy = sinon.spy(window.dataLayer, 'push');
assert.called(spy);
assert.calledWith(spy, [
'fail for me',
]);
spy.restore();
}));
});
这是浏览器类:
const puppeteer = require('puppeteer');
/**
* This is a thin wrapper so that we use a singleton of
* the browser that puppeteer creates
*/
class Browser {
setUp(done) {
const puppeteerOpts = this.options && this.options.puppeteer ?
this.options.puppeteer :
{};
puppeteer.launch(puppeteerOpts).then(async (b) => {
this.setBrowser(b);
done();
});
}
setBrowser(b) {
this.browser = b;
const oldNewPage = this.browser.newPage.bind(this.browser);
this.browser.newPage = async function () {
const page = await oldNewPage();
this.lastPage = page;
return page;
};
}
setOptions(opts) {
this.options = opts;
}
test(promise) {
return (done) => {
promise(this.browser, this.options)
.then(() => done()).catch(done);
};
}
}
/*
* Create a new browser and use a proxy to pass
* any puppeteer calls to the inner browser
*/
module.exports = new Proxy(new Browser(), {
get(target, name) {
return name in target ? target[name].bind(target) : target.browser[name];
},
});