Rayrun
← Back to Discord Forum

Is there any way to retrieve(in the test context) constant created in the the fixture?

I got a fixture where the string constant is build based on the fixture parameter passed to it. How can I retrieve this build value from the fixture?

defaultNamePrefix: ['AT NAME', { option: true }],
    createBasicReportAndSave: async (
        {
            openedReportsSettingsScreen: reportSettingsScreen,
            defaultNamePrefix
        },
        use
    ) => {
        const maxRepNameLength = 32;
        const defaultReportNamePrefix = 'AT ';
        const reportName = `${defaultNamePrefix}${faker.string.alphanumeric(maxRepNameLength - defaultReportNamePrefix.length)}`;
        //do something and return "reportName" to be used in the test context
        use(reportSettingsScreen);
    },

This thread is trying to answer question "How can I retrieve a string constant built based on a fixture parameter from the fixture and use it in the test context?"

0 replies

Answer

Sure, you can retrieve a string constant from a fixture parameter and use it in your test context with @playwright/test. Here's how:

First, define a fixture with the necessary parameters and logic to build the string constant. Let's call this fixture myFixture and it takes a parameter fixtureParam.

const myFixture = base.extend<{ fixtureParam: string }>({
  myFixture: [async ({}, use) => {
    const myStringConstant = 'Hello ' + 'World'; // Replace with actual logic
    await use(myStringConstant);
  }],
});

Next, extend the base test function from Playwright Test (test) to create your own test function. This allows you to include custom fixtures in your tests.

const myTest = myFixtures.test;

In your custom test function, include myFixture as one of the arguments. Playwright Test will automatically resolve and provide an instance of myFixture when running your tests.

myTest('example test', async ({ myFixture }) => {
  const stringConstant = myFixture;
  console.log(stringConstant); // Output: 'Hello World'
});

In this example, myFixture is a custom fixture that takes a parameter fixtureParam. You define the logic to build or retrieve your desired string constant based on fixtureParam inside myFixture. The resolved instance of myFixture is then passed as an argument to your custom test function, where you can access and use the retrieved string constant.

For more details on using fixtures in @playwright/test, check out Mastering Playwright Test Automation: Your Comprehensive Cheat Sheet.

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].