【问题标题】:Playwright before each for all spec files剧作家之前的所有规范文件
【发布时间】:2022-01-12 15:34:54
【问题描述】:

我对剧作家很陌生。由于我的测试套件,我需要在运行每个测试之前登录我的应用程序。在一个简单的规范文件中,我可以简单地调用test.beforeEach。我的问题是:我需要在登录之前对每个规范文件进行每次测试。

test.describe('Test', () => {
    //I need to make the code inside this beforeEach a exported 
    //function to call inside the before each of every spec file I have
    test.beforeEach(async ({ page }) => {
        await page.goto('/login');
        await page.click('text=Log in with Google account');
        await page.fill('id=identifierId', LoginAutomationCredentials.USER);
        await page.click('button[jsname="LgbsSe"]');
        await page.fill('input[type="password"]', LoginAutomationCredentials.PASSWORD);
        await page.click('button[jsname="LgbsSe"]');
        const otp = authenticator.generateToken(LoginAutomationCredentials.TOKEN);
        await page.fill('id=totpPin', otp);
        await page.click('button[jsname="LgbsSe"]');
    });

    it('Some description', async ({ page }) => {
        await page.goto('/foo');
        const dateFilter = await page.inputValue('input[placeholder="2011/03/02"]');
        expect(dateFilter).toBe('2021/12/07');
    });
});

我尝试简单地获取该代码并将其作为单独的 .ts 文件中的函数,然后将其导入,但我认为需要上下文才能执行此操作。这可能是每个使用剧作家的测试人员都知道并经常使用的东西,但是,我没有找到任何关于这个主题的东西。

如何避免复制beforeEach 的整个代码并将其粘贴到我的所有规范文件中?我怎样才能让它成为一个函数并在我想要的时候调用它?

【问题讨论】:

  • 为什么不直接使用全局设置和重用身份验证?您也可以尝试使用固定装置,创建登录固定装置并传递它而不是页面固定装置。

标签: javascript typescript automated-tests playwright playwright-test


【解决方案1】:

使用固定装置。

fixture.js:

const base = require('@playwright/test')
const newTest = base.test.extend({
    login: async({page}, use) => {
        await login();
        await use(page); //runs test here
        //logic after test
    }
})
exports.newTest = newTest
exports.expect = newTest.expect

然后在你的测试中:

const {newTest} = require('fixture.js')
newTest('mytest', async ({login}) => {
    //test logic
    login.goto(''); // using login here since I pass it as page in the fixture.
})

【讨论】:

    猜你喜欢
    • 2022-12-10
    • 2021-09-28
    • 2020-10-08
    • 1970-01-01
    • 2023-01-19
    • 2021-12-28
    • 2022-07-20
    • 2021-02-19
    • 2021-08-02
    相关资源
    最近更新 更多