1 | import request = require('request');
|
2 | import { requestJSON } from './request';
|
3 |
|
4 | export class TestSession {
|
5 | private jar = request.jar();
|
6 | constructor(public port: number) {}
|
7 | async query<T>(query: string, error = '', result?: {}): Promise<T> {
|
8 | const res = await this.request<{ data: T; errors: {}[] }>('post', '/api/graphql', { query });
|
9 | const errorMsg = res.data.errors && res.data.errors[0];
|
10 |
|
11 | if (error) {
|
12 | if (!errorMsg) throw new Error(`Should be error: "${error}", got nothing, query: ${query}`);
|
13 | if (error !== errorMsg)
|
14 | throw new Error(`Should be error: "${error}", got: ${JSON.stringify(errorMsg)}, query: ${query}`);
|
15 | } else {
|
16 |
|
17 | if (errorMsg) throw new Error(`Unexpected error: ${JSON.stringify(errorMsg)}, query: ${query}`);
|
18 | }
|
19 |
|
20 | if (result && JSON.stringify(result) !== JSON.stringify(res.data)) {
|
21 | const got = JSON.stringify(res.data);
|
22 | const expect = JSON.stringify(result);
|
23 | throw new Error(`Result is not the same: \n${expect}\ngot:\n${got}\nquery: ${query}`);
|
24 | }
|
25 | return res.data.data;
|
26 | }
|
27 | request<T>(method: string, url: string, json?: {}) {
|
28 | return requestJSON<T>(`http://localhost:${this.port}${url}`, { method, jar: this.jar, json });
|
29 | }
|
30 | }
|
31 |
|
32 |
|