如何重用puppeteer测试

时间:2018-06-08 07:51:25

标签: testing jestjs puppeteer end-to-end

我目前正在与Puppeteer和Jest一起进行端到端测试,因为我的测试工作我总是需要运行登录测试,但我不知道并且无法了解如何导出我的测试,以便我可以重复使用它们。

总结:我正在寻找一种方法,通过将它们导出到另一个文件并在新文件中的beforeAll中重用它们来重用我在describe中的所有测试。

完整的登录测试集如下:

describe("homepage and login tests", homepageTests = () => {

    test("front page loads", async (done) => {
        await thePage.goto('http://localhost:3000');
        expect(thePage).toBeDefined();
        done();
    });

    test("Login button is present", async (done) => {
        theLoginButton = await thePage.$("#login-button");
        expect(theLoginButton).toBeDefined();
        done();
    })

    test("Login works", async (done) => {
        //the following code runs inside the popup
        await theBrowser.on('targetcreated', async (target) => {
            const thePopupPage = await target.page();
            if (thePopupPage === null) return;

            //get the input fields
            const usernameField = await thePopupPage.waitFor('input[name=login]');
            const passwordField = await thePopupPage.waitFor("input[name=password]");
            const submitButton = await thePopupPage.waitFor('input[name=commit]');

            //validate input fields
            expect(usernameField).not.toBeNull();
            expect(passwordField).not.toBeNull();
            expect(submitButton).not.toBeNull();

            //typing and clicking
            await thePopupPage.waitFor(300)
            await usernameField.type("USER");
            await passwordField.type("PASSWORD");
            await submitButton.click();
            done();
        })

        try {
            //wait for login button on homepage
            theLoginButton = await thePage.waitFor('#login-button');
            expect(theLoginButton).toBeDefined();

            //click on login
            await thePage.waitFor(200);
            await theLoginButton.click();

        } catch (e) { console.log(e) }
    })

    test("Arrive on new page after login", async () => {
        //resultsButton is only shown for logged in users.
        const resultsButton = await thePage.$("#resultsButton");
        expect(resultsButton).toBeDefined();
    })

1 个答案:

答案 0 :(得分:0)

创建一个单独的文件名test.js

// test.js

export async function fn1(args){
   // your commands
}

// file.test.js

import {fn1} from 'test.js'

describe('test 1 ', () => {
test("test", async () => {

      try {
        await fn1(args);          
      } catch (err) {
        console.log('There are some unexpected errors: ' + err);
      }

  },5000);
});

我有同样的问题,以上方法将为您解决。