/* * Copyright (C) 2018-2020 StApps * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see . */ import {expect} from 'chai'; import {suite, test} from '@testdeck/mocha'; import nock from 'nock'; import {HttpClient} from '../src/http-client.js'; // TODO: use after each to clean up the nock (then there is no need for numerated resource links) @suite() export class HttpClientSpec { @test async construct() { expect(() => { return new HttpClient(); }).not.to.throw(); } async after() { nock.cleanAll(); } @test async request() { const client = new HttpClient(); nock('http://www.example.com').get('/resource').reply(200, 'foo'); const response = await client.request({ url: new URL('http://www.example.com/resource'), }); expect(response.body).to.be.equal('foo'); } @test async requestWithBody() { const client = new HttpClient(); nock('http://www.example.com').get('/resource').reply(200, 'foo'); const response = await client.request({ url: new URL('http://www.example.com/resource'), }); expect(response.body).to.be.equal('foo'); } @test async requestWithError() { const client = new HttpClient(); let caughtErr; nock('http://www.example.com').get('/resource').replyWithError('foo'); try { await client.request({ body: { foo: 'bar', }, url: new URL('http://www.example.com/resource'), }); } catch (err) { caughtErr = err; } expect(caughtErr).not.to.be.undefined; } @test async requestWithHeaders() { const client = new HttpClient(); nock('http://www.example.com').get('/resource').reply(200, 'foo'); const response = await client.request({ headers: { 'X-StApps-Version': 'foo.bar.foobar', }, url: new URL('http://www.example.com/resource'), }); expect(response.body).to.be.equal('foo'); } @test async requestWithMethodGet() { const client = new HttpClient(); nock('http://www.example.com').get('/resource').reply(200, 'foo'); const response = await client.request({ method: 'GET', url: new URL('http://www.example.com/resource'), }); expect(response.body).to.be.equal('foo'); } @test async requestWithMethodPost() { const client = new HttpClient(); nock('http://www.example.com').post('/resource').reply(200, 'foo'); const response = await client.request({ method: 'POST', url: new URL('http://www.example.com/resource'), }); expect(response.body).to.be.equal('foo'); } }