I’m new to TypeScript and working on a Playwright-Test-Project for Accessibility-Testing with the axe-core package.
It all works fine, but I dont get some parts of the code and I hate this feeling of not knowing what is actually going on.
So maybe you guys can help me 🙂
import { test as base } from '@playwright/test';
import AxeBuilder from '@axe-core/playwright';
type AxeFixture = {
makeAxeBuilder: () => AxeBuilder;
};
// Extend base test by providing "makeAxeBuilder"
//
// This new "test" can be used in multiple test files, and each of them will get
// a consistently configured AxeBuilder instance.
export const test = base.extend<AxeFixture>({
makeAxeBuilder: async ({ page }, use, testInfo) => {
const makeAxeBuilder = () => new AxeBuilder({ page })
.withTags(['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa'])
.exclude('#commonly-reused-element-with-known-issue');
await use(makeAxeBuilder);
}
});
export { expect } from '@playwright/test';
This is the code snipped from Playwright Fixtures I want to understand.
I’m coming from Java so I know the basics of OO-programming. And I think I got the concept of callback-functions (they play a big role in JS/TS If I got it right).
But I dont get this code. Maybe it’s a good idea if I give my explanation so you can correct me?
So let’s go 🙂
First we import some stuff from playwright.
Than we define a type ‘AxeFixture’. I explained this type-concept for me as something like a blueprint for an Object similiar as an Interface. This should contain a function that returns an AxeBuilder-Object.
Than we use an alias for the test-object (‘base’) to extend the actual test-object. The extend-method may accept a parameter of our defined AxeFixture-Type. Since our Type ‘AxeFixture’ requires the method ‘makeAxeBuilder’ we implement this now in: makeAxeBuilder: async ({ page }, use) => {...}
This method contains get 2 parameters: the page-object and a use-function.
On this point the naming is a bit confusing, since the required function and the variable have the same name: makeAxeBuilder.
Nevertheless, we now define the function makeAxeBuilder and than save the reference to the function in the variable makeAxeBuilder.
In the function body, we build a new AxeBuilder-Object and configure it with some WCAG-Tags. And finally we pass this object to the use-function (this does some magic?)
Overall, we extended the test-object of playwright with an function, that returns an AxeBuilder-Object that we can now use in our tests, if we call the function.
test('MyTest', async ({page, makeAxeBuilder}) => {
await page.goto('/')
const axeBuilder = makeAxeBuilder()
...
}
I would be really happy for feedback. As I already said: I’m still a learner but I want to understand the concepts. 🙂
Please see my details
Max Mustermann is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.