Search code examples
testingwebdriverautomated-teststestcafebrowser-automation

Testcafe Accessibility test as a module


I am trying to include Testcafe aXe tests as a module as follows:

// a11y.js
const { axeCheck, createReport } = require('axe-testcafe');

const a11y = async t => {
  const { error, violations } = await axeCheck(t);
  await t.expect(violations.length === 0).ok(createReport(violations));
};

module.exports = {
  a11y
};

then import in my test file as follows:

// mytest.js
const myModule = require('a11y.js');

fixture `TestCafe tests with Axe`
    .page `http://example.com`;

test('Automated accessibility testing', async t => {
    await a11y();
});

The goal is to centralize all tests in this module (there are a bunch of files and tests) and expose the functions to be used everywhere else.

However, I am getting the following error, which based on the read is because axeCheck(t) has to be inside a test.

Automated accessibility testing

   1) with cannot implicitly resolve the test run in context of which it should be executed. If you need to call with from the Node.js API
      callback, pass the test controller manually via with's `.with({ boundTestRun: t })` method first. Note that you cannot execute with outside
      the test code.

Can this be solved by calling .with({ boundTestRun: t })? If so, where do I insert that code?


Solution

  • You need to pass the TestController object as a parameter of the a11() function. So, your code will look as follows:

    // a11y.js
    
    const { axeCheck, createReport } = require('axe-testcafe');
    
    const a11y = async t => {
        const { violations } = await axeCheck(t);
    
        await t.expect(violations.length === 0).ok(createReport(violations));
    };
    
    module.exports = a11y;
    
    
    // test.js
    const a11y = require('./a11y.js');
    
    fixture `Fixture`
        .page('http://example.com');
    
    test('test', async t => {
        await a11y(t);
    });