简体   繁体   中英

How to add custom request header to testcafe test suite?

I have a bunch of tests that I am running through testcafe. Now I need to add a custom request header for each test that uniquely identifies the call is originating from the testcafe suite and not a real user.

Is there a way to add the custom header to all the test cases at once?

I was looking at this but it seems like I would need to update each fixture to get this working. So, I wanted to know if there's a way I can set it on a top level file before calling the test suite?

EDIT:

So, this is what I am currently doing. I have created a new file that contains the class:

import { RequestHook } from 'testcafe';

class CustomHeader extends RequestHook {
    constructor () {
        // No URL filtering applied to this hook
        // so it will be used for all requests.
        super();
    }
    
    onRequest (e) {
        e.requestOptions.headers['my_custom_variable'] = 'my_value';
    }

    onResponse (e) {
        // This method must also be overridden,
        // but you can leave it blank.
    }
}

const customHeader = new CustomHeader();
export default customHeader;

And then in my each test file, update the fixtures to be like this:

import { customHeader } from 'customer_header'

fixture(`Test app avail`)
  .page(appURL)
  .requestHooks(customHeader)
  .beforeEach(async() => {
    await myTestfunction();
  });

Does this make sense?

Currently there is no way to specify hooks on the test run level. But, if updating each fixture is not reasonable in your case, you can use the workaround posted in the discussion about this feature. In order to apply your request hook to each fixture in the test suite you'll need to change "setup.js" (from the workaround above) as follows:

export const fixture = (...args) => global.fixture(...args)
    .requestHooks(customHeader)
    .beforeEach(async t => {
        console.log('each');
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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