Files
openstapps/test/http-client.spec.ts
2020-12-17 10:38:30 +01:00

139 lines
3.1 KiB
TypeScript

/*
* 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 <https://www.gnu.org/licenses/>.
*/
import {expect} from 'chai';
import {suite, test} from '@testdeck/mocha';
import nock from 'nock';
import {HttpClient} from '../src/http-client';
// 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');
}
}