简体   繁体   English

如何记录所有赛普拉斯请求的 HTTP 响应 header 值?

[英]How to log HTTP response header value for all cypress requests?

One of my ideas would be to overwrite the request command, but I don't know how to handle the response object.我的想法之一是覆盖请求命令,但我不知道如何处理响应 object。 A snippet I already have:我已经有一个片段:

Cypress.Commands.overwrite(
    'request',
    (
        originalFn: Cypress.CommandOriginalFn<'request'>,
        options: Partial<Cypress.RequestOptions>
    ): void | Cypress.Chainable<Cypress.Response<unknown>> => {
        return originalFn(options);
    }
);

My other idea would be to intercept all requests, but there are already interceptors added and you can not have two for one request.我的另一个想法是拦截所有请求,但是已经添加了拦截器,一个请求不能有两个。

beforeEach(() => {
    cy.intercept(
        {
            url: '*/**',
        },
        req => {
            // tried with 'after:response' too
            req.on('response', res => {
                cy.log(`${res.headers['x-custom-header']}`);
            });
        }
    );
});

Is there any other way to log a custom header value for all request?有没有其他方法可以为所有请求记录自定义 header 值?

My final working solution was to add this code to /support/index.ts我最终的工作解决方案是将此代码添加到/support/index.ts

beforeEach(() => {
    cy.intercept({ url: '*', middleware: true }, req => {
        req.on('after:response', (res => {
            const customHeaderKey = 'x-custom-header';
            const customHeaderValue = res.headers[customHeaderKey];
            if (customHeaderValue) {
                const message = JSON.stringify({ [customHeaderKey]: customHeaderValue });
                Cypress.log({ message }).finish();
            }
        }));
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM