如何通过参数将自定义标头设置为Chrome应用

问题描述

作为自动化测试的一部分,我想借助自定义标题testcafe测试指向Test Prod服务器(绿色)。

在启动以作为参数执行测试时,如何将自定义标头传递给chrome实例。

尝试使用chrome:userProfile,但标题在每个发行版中都会更改。

需要一种通用的方式来传递自定义标头。

注意:更改testcafe脚本不是可取的。

解决方法

Google Chrome浏览器不允许从命令行设置请求标头,但是您可以使用请求挂钩根据环境变量添加标头值。

请参考以下示例。请注意,RequestLogger仅出于演示目的而添加:


// test.js

import { RequestLogger,RequestHook } from 'testcafe';

fixture `Set a Custom Referer`
    .page`http://example.com/`;

export class MyRequestHook extends RequestHook {
    constructor(requestFilterRules,responseEventConfigureOpts) {
        super(requestFilterRules,responseEventConfigureOpts);
    }
    async onRequest(event) {
        event.requestOptions.headers['CustomHeader'] =  process.env.HEADER_VALUE;
    }

    async onResponse(event) {

    }
}

const hook   = new MyRequestHook();
const logger = RequestLogger(
    ["https://devexpress.github.io/testcafe/example/","http://example.com/"],{
        logRequestHeaders: true,}
);

test
    .requestHooks([hook,logger])
    ('Check the Referer Value',async t => {
        await t
            .navigateTo('https://devexpress.github.io/testcafe/example/')
            .expect(logger.contains(r => r.request.url === 'https://devexpress.github.io/testcafe/example/')).ok()
            .expect(logger.requests[0].request.headers['CustomHeader']).eql(process.env.HEADER_VALUE);
    });

现在,您可以使用以下命令(POSIX)在测试服务器上运行测试:

export HEADER_VALUE='my value'
testcafe chrome test.js

有关更多信息,请参阅此文档主题:event delegation