Я пытаюсь автоматически протестировать код отслеживания и использую RequestLogger от Testcafé. Мне удалось перехватить звонки на example.com и localhost, но не на https://www.google-analytics.com/. Что может быть причиной?
import { RequestLogger } from 'testcafe';
const logger_ga = RequestLogger('https://www.google-analytics.com/');
fixture `localhost`
.page('http://localhost:8000')
test
.requestHooks(logger_ga)
('logs calls to Google Analytics', async t => {
await t.click("#ga-button");
console.info(logger_ga.requests); // is empty due to timing
await t.expect(logger_ga.contains(record => record.response.statusCode === 200)).ok();
});
Я обслуживаю следующую страницу index.html через python -m SimpleHTTPServer 8000
<!doctype html>
<html>
<head>
<meta charset = "utf-8">
<title>Test page</title>
</head>
<body>
<p>Hello world!</p>
<!-- Google Analytics: change UA-XXXXX-Y to be your site's ID. -->
<script>
window.ga = function () { ga.q.push(arguments) }; ga.q = []; ga.l = +new Date;
ga('create', 'UA-XXXXX-Y', 'auto'); ga('send', 'pageview')
</script>
<script src = "https://www.google-analytics.com/analytics.js" async defer></script>
<a onclick = "ga('send', 'event', 'my_event_category', 'my_event_action', 'my_event_label');" href = "#" id = "ga-button">Google Analytics</a>
</body>
</html>
import { RequestLogger } from 'testcafe';
const logger = RequestLogger('http://example.com');
fixture `example`
.page('http://example.com');
test
.requestHooks(logger)
('logs calls to example.com', async t => {
await t.expect(logger.contains(record => record.response.statusCode === 200)).ok(); // green
});
const logger_localhost = RequestLogger('http://localhost:8000');
fixture `localhost`
.page('http://localhost:8000');
test
.requestHooks(logger_localhost)
('logs calls to localhost', async t => {
await t.expect(logger_localhost.contains(record => record.response.statusCode === 200)).ok(); // green
});
Как я могу успешно перехватывать звонки в Google Analytics?





Как предположила Марион, это, вероятно, связано со сроками. Следующий код работает:
import { Selector, RequestLogger } from 'testcafe';
const gaCollect = 'https://www.google-analytics.com/collect';
const gaLogger = RequestLogger({gaCollect}, {
logRequestHeaders: true,
logRequestBody: true,
});
fixture `Fixture`
.page('http://localhost:8000')
.requestHooks(gaLogger);
test('Log Google Analytics call', async t => {
await t.click('#ga-button')
await t.expect(gaLogger.contains(record =>
record.request.url.match(/ec=my_event_category&ea=my_event_action&el=my_event_label/))).ok();
for(let r of gaLogger.requests) {
console.info("*** logger url: ", r.request.url);
}
});
Упомянутый фактор времени @Marion, похоже, играет роль. Сравните предыдущее со следующим фрагментом и его выводом. Здесь мы не видим вызовов, зарегистрированных в https://google-analytics.com/collect.
fixture `Fixture`
.page('http://localhost:8000')
.requestHooks(gaLogger);
test('Log Google Analytics call', async t => {
await t.click('#ga-button')
for(let r of gaLogger.requests) {
console.info("*** logger url: ", r.request.url);
}
await t.expect(gaLogger.contains(record =>
record.request.url.match(/ec=my_event_category&ea=my_event_action&el=my_event_label/))).ok();
});
Возможно, проблема связана с тайм-аутами TestCafe: t.expect ждет 3 секунды, и этого времени может быть недостаточно для загрузки ресурса. Попробуйте вызвать «wait» перед «ожидать»: await t.wait (4000) .expect (logger.contains (record => record.response.statusCode === 200)). Ok ();