UNPKG

1.27 kBPlain TextView Raw
1import request = require('request');
2import { requestJSON } from './request';
3
4export 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 /* istanbul ignore next */
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 /* istanbul ignore next */
17 if (errorMsg) throw new Error(`Unexpected error: ${JSON.stringify(errorMsg)}, query: ${query}`);
18 }
19 /* istanbul ignore next */
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