首页 > 解决方案 > 如何通过参数将自定义标头设置为 chrome 应用程序

问题描述

作为自动化测试的一部分,我想在 Custom Headers 的帮助下将我的 Testcafe 测试指向一个 Test Prod 服务器(绿色)。

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

尝试过 chrome:userProfile 但每个版本的标题都会更改。

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

注意:Testcafe 脚本更改不可取。

标签: google-chrometestingtestcafecustom-headersblue-green-deployment

解决方案


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

请参阅此文档主题以获取更多信息:创建自定义请求挂钩


推荐阅读