authFixture.ts
1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { test as base, Page } from '@playwright/test';
import path from 'path';
/**
* 认证夹具类型定义
*/
type AuthFixtures = {
/**
* 已认证的页面(使用保存的 auth.json)
*/
authenticatedPage: Page;
/**
* 认证文件路径
*/
authFilePath: string;
};
/**
* 扩展的测试对象,包含认证夹具
*/
export const test = base.extend<AuthFixtures>({
// 默认认证文件路径
authFilePath: async ({}, use) => {
await use(path.join(process.cwd(), 'auth.json'));
},
// 已认证的页面
authenticatedPage: async ({ browser, authFilePath }, use) => {
// 创建带有认证状态的上下文
const context = await browser.newContext({
storageState: authFilePath,
});
const page = await context.newPage();
// 使用页面
await use(page);
// 清理
await context.close();
},
});
/**
* 导出 expect 以便在测试中使用
*/
export { expect } from '@playwright/test';
/**
* 创建一个新的认证夹具,使用自定义认证文件路径
* @param authPath 认证文件路径
*/
export function createAuthTest(authPath: string) {
return base.extend<AuthFixtures>({
authFilePath: async ({}, use) => {
await use(authPath);
},
authenticatedPage: async ({ browser, authFilePath }, use) => {
const context = await browser.newContext({
storageState: authFilePath,
});
const page = await context.newPage();
await use(page);
await context.close();
},
});
}