我目前正在使用 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();
})
最佳答案
创建一个单独的文件名test.js
//测试.js
export async function fn1(args){
// your commands
}
//文件.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);
});
我也遇到了同样的问题,上面的方法可以解决。
关于testing - 如何重用 puppeteer 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50755896/