测试应用添加的页面
/a/${pluginId}/
路由可用,允许您访问由应用添加的页面。为了避免重复以及在测试中导入 plugin.json
的需要,有一组页面类和导航函数可用。
本指南将向您展示如何创建特定于应用的 fixture,以便更容易编写测试并在不同测试之间共享逻辑。
具有基本 UI 的页面
如果您想测试一个具有基本 UI 且易于通过标准 Playwright API 进行交互的页面,请使用 gotoPage
等导航函数。
例如
fixtures.ts
import { AppPage, test as base } from '@grafana/plugin-e2e';
import pluginJson from '../src/plugin.json';
type AppTestFixture = {
gotoPage: (path?: string) => Promise<AppPage>;
};
export const test = base.extend<AppTestFixture>({
gotoPage: async ({ gotoAppPage }, use) => {
await use((path) =>
gotoAppPage({
path,
pluginId: pluginJson.id,
})
);
},
});
export { expect } from '@grafana/plugin-e2e';
要使用此函数,只需从您的 fixture 导入 test
和 expect
,而不是从 @grafana/plugin-e2e
导入,然后像往常一样编写您的测试。
例如
startPage.spec.ts
import { test, expect } from './fixtures.ts';
test('start page should welcome users to the app', async ({ gotoPage, page }) => {
await gotoPage('/start');
await expect(page.getByRole('heading', { name: 'Welcome to my app' })).toBeVisible();
});
具有复杂 UI 的页面
另一方面,如果您有一个具有复杂 UI 且可能不易通过标准 Playwright API 进行交互的页面,则需要采用不同的方法。最佳实践是创建一个页面对象,将页面的逻辑封装在函数中。
如果您想在多个测试中重用选择器逻辑,这尤其有用。下面的示例展示了如何使用页面对象扩展标准 fixture。我们简化了 getWelcomeText
逻辑,以突出显示页面对象模式,而不会给本示例引入不必要的复杂性。
例如
fixtures.ts
import { AppPage, PluginTestCtx, PluginPageArgs, test as base } from '@grafana/plugin-e2e';
import pluginJson from '../src/plugin.json';
class StartPage extends AppPage {
private path: string;
constructor(ctx: PluginTestCtx, args: PluginPageArgs & { path: string }) {
super(ctx, args);
this.path = args.path;
}
goto(): Promise<void> {
return super.goto({ path: this.path });
}
getWelcomeText(): Locator {
const { page } = this.ctx;
return page.getByRole('heading', { name: 'Welcome to my app' });
}
}
type AppTestFixture = {
startPage: StartPage;
};
export const test = base.extend<AppTestFixture>({
startPage: async ({ page, selectors, grafanaVersion, request }, use, testInfo) => {
const startPage = new StartPage(
{ page, selectors, grafanaVersion, request, testInfo },
{
pluginId: pluginJson.id,
path: '/start',
}
);
await startPage.goto();
await use(startPage);
},
});
export { expect } from '@grafana/plugin-e2e';
要使用此代码,您只需从您的 fixture 导入 test
和 expect
,而不是从 @grafana/plugin-e2e
导入,然后像往常一样编写您的测试。当您在测试函数中解构 startPage
时,测试会自动导航到该页面。
例如
startPage.spec.ts
import { test, expect } from './fixtures.ts';
test('start page should welcome users to the app', async ({ startPage }) => {
await expect(startPage.getWelcomeText()).toBeVisible();
});