I am learning Playwright and trying to pass value of data from one test block to other test block in test runner. Code as follows:
let text = "some text";
let arr = [];
let num;
function data(name) {
text = name;
arr.push(text);
console.log(text);
num=text;
}
test.describe("test", async () => {
test.beforeAll(async () => {
const browser = await chromium.launch();
const context = await browser.newContext();
page = await context.newPage();
await page.goto("https://google.com/");
console.log("beforeall");
});
// test.beforeEach(async () => {
// console.log("before each");
// });
test("Navigate to Google", async () => {
data("ANNA");
const url = await page.url();
expect(url).not.toContain("google");
});
test("Search for Playwright", async () => {
console.log(arr);
await page.type('input[name="q"]', "Playwright");
await page.keyboard.press("Enter");
console.log(num);
});
});
If first test block "Navigate to block" is passing then I am getting correct value of "num" which is "Anna" in Second test block. But if First test block is failing then same "num" is showing "undefined" in second test Block. I tried same for "arr". (I know I did some repeatable coding its just for experimentation purpose)
Output:(fail)
[Microsoft Edge] › Demo_testscript.spec.js:96:3 › test › Navigate to Google
beforeall
ANNA
[ 'ANNA' ]
1) [Microsoft Edge] › Demo_testscript.spec.js:96:3 › test › Navigate to Google ===================
Error: expect(received).not.toContain(expected) // indexOf
Expected substring: not "google"
Received string: "https://www.google.com/"
98 |
99 | const url = await page.url();
> 100 | expect(url).not.toContain("google");
| ^
101 | });
102 |
103 | test("Search for Playwright", async () => {
at C:\Users\piyus\Desktop\Playwright_framework\tests\Demo_testscript.spec.js:100:21
attachment #1: trace (application/zip) ---------------------------------------------------------
test-results\Demo_testscript-test-Navigate-to-Google-Microsoft-Edge\trace.zip
Usage:
npx playwright show-trace test-results\Demo_testscript-test-Navigate-to-Google-Microsoft-Edge\trace.zip
------------------------------------------------------------------------------------------------
attachment #2: screenshot (image/png) ----------------------------------------------------------
test-results\Demo_testscript-test-Navigate-to-Google-Microsoft-Edge\test-failed-1.png
------------------------------------------------------------------------------------------------
[Microsoft Edge] › Demo_testscript.spec.js:103:3 › test › Search for Playwright
beforeall
[]
some text
undefined
1 failed
[Microsoft Edge] › Demo_testscript.spec.js:96:3 › test › Navigate to Google ====================
1 passed (10s)
OutPut :(pass : by removing not from first test block)
Running 2 tests using 1 worker
[Microsoft Edge] › Demo_testscript.spec.js:96:3 › test › Navigate to Google
beforeall
ANNA
[ 'ANNA' ]
[Microsoft Edge] › Demo_testscript.spec.js:103:3 › test › Search for Playwright
[ 'ANNA' ]
ANNA
ANNA
2 passed (6s)```