-
Notifications
You must be signed in to change notification settings - Fork 0
/
mock-helper.ts
68 lines (56 loc) · 1.8 KB
/
mock-helper.ts
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
import { Page } from "@playwright/test";
import path from "path";
import fs from 'fs';
export class MockHelper {
page: Page;
rootDirectory: string;
dataType: 'xml' | 'json';
/**
*
* @param page reference to the playwright page
* @param rootDirectory the base directory of th mock files
* @param datatype currently json and xml reponspe types are supported default is json
*/
constructor(page: Page, rootDirectory: string, dataType?: 'xml' | 'json') {
this.page = page;
this.rootDirectory = rootDirectory;
this.dataType = dataType ?? 'json';
}
/**
* Method to mock an endpoint and optional return a <scenario> placed in the rootdir
* Default returns empty response and status code 200 can be changed via MockEndpoint object properties
*
* @param endpoint
*
*/
async mockEndpoint(endpoint: MockEndpoint) {
const responseBody = this.getResponseBody(endpoint);
await this.page.route(new RegExp(endpoint.url), route =>
route.fulfill({
headers: { 'content-type': `application/${this.dataType}`, 'access-control-allow-origin': '*' },
body: responseBody ?? '',
status: endpoint.statusCode ?? 200
}));
}
private getResponseBody(endpoint: MockEndpoint): string {
if (endpoint.scenario && endpoint.mockDir){
const bodyPath = path.resolve(this.rootDirectory, endpoint.mockDir, `${endpoint.scenario}.${this.dataType}`);
return fs.readFileSync(bodyPath, 'utf-8');
} else {
return '';
}
}
}
/**
* url regex of the server url to mock
* mockDir directory containing the mock scenarios optional
* scenario name of the reponse file optional
* statusCode reponse code optional
*
*/
export interface MockEndpoint {
url: string,
mockDir?: string,
scenario?: string,
statusCode?: number
}