/* * 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 nock from 'nock'; import {HttpClient} from '../src/index.js'; // TODO: use after each to clean up the nock (then there is no need for numerated resource links) describe('HttpClient', function () { afterEach(function () { nock.cleanAll(); }) it('should construct', function () { expect(() => { return new HttpClient(); }).not.to.throw(); }); it('should request', async function () { 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'); }); it('should request with body', async function () { 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'); }); it('should request with error', async function () { const client = new HttpClient(); let caughtError; 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 (error) { caughtError = error; } expect(caughtError).not.to.be.undefined; }); it('should request with headers', async function () { 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'); }); it('should request with method GET', async function () { 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'); }); it('should request with method POST', async function () { 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'); }); });