Skip to content

Commit

Permalink
chore: add “Invalid JSON” test
Browse files Browse the repository at this point in the history
  • Loading branch information
lukeed committed May 13, 2019
1 parent 3535f34 commit b493649
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
22 changes: 20 additions & 2 deletions test/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import test from 'tape';
import { parse, URL } from 'url';
import * as httpie from '../src';
import server from './server';

// Demo: https://reqres.in/api
function isResponse(t, res, code, expected) {
Expand Down Expand Up @@ -43,11 +44,11 @@ test('GET (404)', async t => {
t.true(err instanceof Error, '~> returns a true Error instance');
t.is(err.message, err.statusMessage, '~> the "message" and "statusMessage" are identical');
t.is(err.message, 'Not Found', '~~> Not Found');
isResponse(t, err, 404, {});
isResponse(t, err, 404, {}); // +6
}
});

test('POST 201', async t => {
test('POST (201)', async t => {
t.plan(9);

let body = {
Expand Down Expand Up @@ -192,3 +193,20 @@ test('via URL (WHATWG)', async t => {
let res = await httpie.get(foo);
isResponse(t, res, 200);
});

test('Error: Invalid JSON', async t => {
t.plan(7);
let ctx = await server();
await httpie.get(`http://localhost:${ctx.port}/any`).catch(err => {
t.true(err instanceof SyntaxError, '~> caught SyntaxError');
t.true(err.message.includes('Unexpected token'), '~> had "Unexpected token" message');
t.true(err.stack.includes('JSON.parse'), '~> printed `JSON.parse` in stack');

t.is(err.statusCode, 200, `~> statusCode = 200`);
t.ok(err.headers['content-type'], `~> headers['content-type'] exists`);
t.ok(err.headers['content-length'], `~> headers['content-length'] exists`);
t.is(err.data, undefined, '~> err.data is undefined');

ctx.close();
});
});
15 changes: 15 additions & 0 deletions test/server/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { createServer } from 'http';

function handler(req, res) {
res.setHeader('Content-Type', 'application/json');
res.end('{invalid_json');
}

export default async function () {
return new Promise(res => {
let app = createServer(handler).listen();
let close = app.close.bind(app);
let { port } = app.address();
return res({ port, close });
});
}

0 comments on commit b493649

Please sign in to comment.