How do I add headers to the response in Testcafe? So far I've tried using the onResponse
function of the RequestHook
class. Using a RequestLogger
, I can validate that the headers were added, but they don't actually make it to the browser (not visible in the list of response headers in Chrome's network tab).
Here's what I'm using:
import { RequestLogger, RequestHook } from 'testcafe';
class HeadersHook extends RequestHook {
constructor(requestFilterRules) {
super(requestFilterRules, { includeBody: false, includeHeaders: true });
}
async onRequest(event) { }
async onResponse(event) {
event.headers['bar'] = 'foo';
event.headers.foo = 'bar';
console.log('hook: ', event.headers);
}
}
fixture('My Fixture');
test('Example internal-sdk usage', async (t) => {
const headerLogger = RequestLogger(process.env.TEST_URL, {
logResponseHeaders: true
});
// This order is significant: adding the logger first causes it to miss the additional headers.
// Not sure why.
await t.addRequestHooks(new HeadersHook(process.env.TEST_URL));
await t.addRequestHooks(headerLogger);
await t.navigateTo(process.env.TEST_URL);
console.log('logger: ', headerLogger.requests.length, headerLogger.requests[0].response.headers);
t.debug();
});
This gives the following console output which seems to indicate that the headers were successfully added:
hook: {
'content-type': 'text/html;charset=utf-8',
vary: 'origin,accept-encoding',
'access-control-allow-credentials': 'true',
'access-control-expose-headers': 'WWW-Authenticate,Server-Authorization',
'cache-control': 'no-cache',
'content-encoding': 'gzip',
date: 'Fri, 05 Mar 2021 16:43:06 GMT',
connection: 'keep-alive',
'keep-alive': 'timeout=5',
'transfer-encoding': 'chunked',
bar: 'foo',
foo: 'bar'
}
logger: 1 {
'content-type': 'text/html;charset=utf-8',
vary: 'origin,accept-encoding',
'access-control-allow-credentials': 'true',
'access-control-expose-headers': 'WWW-Authenticate,Server-Authorization',
'cache-control': 'no-cache',
'content-encoding': 'gzip',
date: 'Fri, 05 Mar 2021 16:43:06 GMT',
connection: 'keep-alive',
'keep-alive': 'timeout=5',
'transfer-encoding': 'chunked',
bar: 'foo',
foo: 'bar'
}
But in the browser network tab, all I see is this (additional headers missing):
access-control-allow-credentials: true
access-control-expose-headers: WWW-Authenticate,Server-Authorization
cache-control: no-cache
connection: keep-alive
content-encoding: gzip
content-type: text/html;charset=utf-8
date: Fri, 05 Mar 2021 16:45:51 GMT
keep-alive: timeout=5
transfer-encoding: chunked
vary: origin,accept-encoding