我刚刚进入了使用 puppeteer 和 jest 进行测试的世界,我想知道在文件夹架构和逻辑方面的最佳实践是什么。
我以前从未做过测试,我想我对不同的原则和概念以及它们如何组合在一起有点迷失了。
我学会了基于页面对象模型进行测试,所以我的每个页面都有类,而且我的每个模块(或组件)也有类。例如,在我的应用程序中,标题或登录模式是组件。
然后我每页或每个组件都有一个测试文件。
(例如 landingPage.tests.js
文件,它使用 LandingPage.js
文件中的 LandingPage 类的模型)
这是一个具体的例子:
我有不同的登录案例,我想全部测试一下。例如,我想测试与“普通”用户连接,该过程只是登录然后密码。然后我需要与已激活 2FA 的用户或使用 SSO 的公司的用户一起进行测试。
我首先想到将我的不同测试放在 authentication.tests.js
, 在不同的 describe
block ,认为它每次都会打开一个新标签,但它不会......我在隐身模式下使用 puppeteer 以确保每个标签都是一个独立的 session 。
所以我的问题是:
这里是
authentication.tests.js
,我想在其中测试我所有不同的登录方式:import HeaderComponent from "../../../pages/components/HeaderComponent";
import AuthenticationComponent from "../../../pages/components/AuthenticationComponent";
import LandingPage from "../../../pages/landing/LandingPage";
import {
JEST_TIMEOUT,
CREDENTIALS
} from "../../../config";
describe('Component:Authentication', () => {
let headerComponent;
let authenticationComponent;
let landingPage;
beforeAll(async () => {
jest.setTimeout(JEST_TIMEOUT);
headerComponent = new HeaderComponent;
authenticationComponent = new AuthenticationComponent;
landingPage = new LandingPage;
});
describe('Normal login ', () => {
it('should click on login and open modal', async () => {
await landingPage.visit();
await headerComponent.isVisible();
await headerComponent.clickOnLogin();
await authenticationComponent.isVisible();
});
it('should type a normal user email adress and validate', async () => {
await authenticationComponent.typeUsername(CREDENTIALS.normal.username);
await authenticationComponent.clickNext();
});
it('should type the correct password and validate', async () => {
await authenticationComponent.typePassword(CREDENTIALS.normal.password);
await authenticationComponent.clickNext();
});
it('should be logged in', async () => {
await waitForText(page, 'body', 'Success !');
});
});
describe('SSO login ', () => {
// todo ...
});
});
谢谢,如果这听起来令人困惑,我很抱歉,就像我说的那样,我正试图弄清楚这一切是如何结合在一起的。
最佳答案
关于文件夹结构,Jest 会根据 match config 查找任何文件。 ,基本上任何称为 *.spec.js 或 *.test.js 的东西。看起来你已经知道了。
这意味着文件夹结构完全取决于您。有些人喜欢将组件的测试与组件本身放在相同的文件夹中。就我个人而言,我更喜欢将所有测试放在一个文件夹中,因为它使项目看起来更干净。
将所有测试放在一个文件夹中的另一个好处是,您可以开始区分测试类型。组件测试检查纯组件是否按预期呈现和运行。您不需要 Puppeteer,如果您在 React 应用程序中,请使用快照。 Puppeteer 非常适合使用 headless Chromium 浏览器通过所谓的“快乐路径”、登录、注册、添加到购物车等进行导航的集成测试。
要在每次测试的新页面上回答您在 Jest/Puppeteer 上遇到的具体问题:
//keep a reference to the browser
let browser
//keep a reference to the page
let page
// open puppeteer before all tests
beforeAll(async () => {
browser = await puppeteer.launch()
})
// close puppeteer after all tests
afterAll(async () => {
await browser.close()
})
// Get a new page for each test so that we start fresh.
beforeEach(async () => {
page = await browser.newPage()
})
// Remember to close pages after each test.
afterEach(async () => {
await page.close()
})
describe('Counter', () => {
// "it" blocks go here.
})
希望有点帮助。
关于testing - Jest + puppeteer 最佳架构实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60442366/