简体   繁体   中英

Using multiple test fixtures in a single test with Playwright

// foo.ts
import { test as base } from "@playwright/test";

const test = base.extend<{foo: string}>({
    foo: "hello"
});

export { test };
// bar.ts
import { test as base } from "@playwright/test";

const test = base.extend<{bar: string}>({
    bar: "bye"
});

export { test };
// index.ts
import { test } from /* BOTH_FOO_AND_BAR??? */;

test("Basic test", async ({ foo, bar }) => { // <-- I want to be able to use both foo and bar fixture here
    console.log(foo);
    console.log(bar);
});

Can the above be achieved? Or do I have to have one depends on the other like this?

// bar.ts
import { test as base } from "./foo";
// index.ts
import { test } from "./bar";

This will create a long chain if I have many files and importing the last file would import all of them. I would prefer pick and match if it is at all possible.

I suggest grouping fixtures into one file:

// fixtures.ts
import { test as base } from "@playwright/test";

const test = base.extend<{
   foo: string;
   bar: string;

}>({
    foo: "hello",
    bar: "bye"

});
export default test;
export const expect = test.expect;

Then You can import both:

// index.ts
import test, { expect } from "./fixtures";

test("Basic test", async ({ foo, bar }) => { // <-- I want to be able to use both foo and bar fixture here
    console.log(foo);
    console.log(bar);
});

Additional note that could be useful You can chain fixtures here instead of doing that in tests:

// fixtures.ts
import { test as base } from "@playwright/test";
import { MainPage } from "./main-page";
import { FirstPage } from "./firstPage";

const test = base.extend<{
   mainPage: MainPage;
   firstPage: FirstPage;

}>({
    mainPage: async ({ page, baseUrl }, use) => {  //Assuming your mainPage constructor accepts page fixture and baseUrl
    // Some steps to open mainPage
    await use(mainPage);
    },
    firstPage: async ( {mainPage}, use) => {  //Assuming firstPage constructor accepts page fixture
    //do some steps 
    await use(firstPage);
    }

});
export default test;
export const expect = test.expect;

Then You can simply use only first Page without have to write steps for main page, but also mainPage or any other fixture will be avaiable.

// index.ts
import test, { expect } from "./fixtures";

test("Basic test", async ({ firstPage }) => { 
  //do steps
});

Another example from playwright: https://playwright.dev/docs/next/test-fixtures#creating-a-fixture

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