Skip to content

Commit

Permalink
Improve tests (#41)
Browse files Browse the repository at this point in the history
  • Loading branch information
fisker committed Oct 27, 2023
1 parent 789771a commit bb0a503
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 8 deletions.
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@
"devDependencies": {
"ava": "^5.2.0",
"nyc": "^15.1.0",
"outdent": "^0.8.0",
"strip-ansi": "^7.1.0",
"tsd": "^0.28.1",
"xo": "^0.54.0"
}
Expand Down
29 changes: 21 additions & 8 deletions test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import process from 'node:process';
import test from 'ava';
import {outdent} from 'outdent';
import stripAnsi from 'strip-ansi';
import parseJson, {JSONError} from './index.js';

const errorMessageRegex = (() => {
Expand All @@ -16,20 +18,31 @@ const errorMessageRegex = (() => {
return /Expected double-quoted property name in JSON at position 16 \(line 3 column 1\) while parsing/;
})();
const errorMessageRegexWithFileName = new RegExp(errorMessageRegex.source + '.*in foo\\.json');
const INVALID_JSON_STRING = outdent`
{
"foo": true,
}
`;
const EXPECTED_CODE_FRAME = `
1 | {
2 | "foo": true,
> 3 | }
| ^
`.slice(1, -1);

test('main', t => {
t.truthy(parseJson('{"foo": true}'));
t.deepEqual(parseJson('{"foo": true}'), {foo: true});

t.throws(() => {
parseJson('{\n\t"foo": true,\n}');
parseJson(INVALID_JSON_STRING);
}, {
name: 'JSONError',
message: errorMessageRegex,
});

t.throws(() => {
try {
parseJson('{\n\t"foo": true,\n}');
parseJson(INVALID_JSON_STRING);
} catch (error) {
error.fileName = 'foo.json';
throw error;
Expand All @@ -39,14 +52,14 @@ test('main', t => {
});

t.throws(() => {
parseJson('{\n\t"foo": true,\n}', 'foo.json');
parseJson(INVALID_JSON_STRING, 'foo.json');
}, {
message: errorMessageRegexWithFileName,
});

t.throws(() => {
try {
parseJson('{\n\t"foo": true,\n}', 'bar.json');
parseJson(INVALID_JSON_STRING, 'bar.json');
} catch (error) {
error.fileName = 'foo.json';
throw error;
Expand All @@ -66,9 +79,9 @@ test('throws exported error error', t => {

test('has error frame properties', t => {
try {
parseJson('{\n\t"foo": true,\n}', 'foo.json');
parseJson(INVALID_JSON_STRING, 'foo.json');
} catch (error) {
t.assert(error.codeFrame);
t.is(error.rawCodeFrame, ' 1 | {\n 2 | \t"foo": true,\n> 3 | }\n | ^');
t.is(error.rawCodeFrame, EXPECTED_CODE_FRAME);
t.is(stripAnsi(error.codeFrame), EXPECTED_CODE_FRAME);
}
});

0 comments on commit bb0a503

Please sign in to comment.