Skip to content

Commit

Permalink
update tests for optional
Browse files Browse the repository at this point in the history
  • Loading branch information
Elias Mulhall committed Aug 20, 2018
1 parent 80de1f0 commit faaa15e
Showing 1 changed file with 40 additions and 7 deletions.
47 changes: 40 additions & 7 deletions test/json-decode.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -399,12 +399,12 @@ describe('dict', () => {
});

describe('optional', () => {
describe('decoding an interface with optional fields', () => {
interface User {
id: number;
isDog?: boolean;
}
interface User {
id: number;
isDog?: boolean;
}

describe('decoding an interface with optional fields', () => {
const decoder = object<User>({
id: number(),
isDog: optional(boolean())
Expand All @@ -426,6 +426,36 @@ describe('optional', () => {
});
});
});

it('supports map', () => {
const decoder = object<User>({
id: number(),
isDog: optional(number()).map(num => num !== 0)
});

expect(decoder.run({id: 1, isDog: 0})).toEqual({ok: true, result: {id: 1, isDog: false}});
expect(decoder.run({id: 1, isDog: 77})).toEqual({ok: true, result: {id: 1, isDog: true}});
expect(decoder.run({id: 1})).toEqual({ok: true, result: {id: 1}});
});

it('supports andThen', () => {
const decoder = object<User>({
id: number(),
isDog: optional(string()).andThen(
dogName =>
dogName.toLowerCase()[0] === 'd'
? succeed(true)
: fail(`${dogName} is not a dog, all dog names start with 'D'`)
)
});

expect(decoder.run({id: 1, isDog: 'Doug'})).toEqual({ok: true, result: {id: 1, isDog: true}});
expect(decoder.run({id: 1, isDog: 'Wanda'})).toMatchObject({
ok: false,
error: {message: "Wanda is not a dog, all dog names start with 'D'"}
});
expect(decoder.run({id: 1})).toEqual({ok: true, result: {id: 1}});
});
});

describe('oneOf', () => {
Expand Down Expand Up @@ -531,7 +561,7 @@ describe('withDefault', () => {
});

describe('valueAt', () => {
describe('decode an value', () => {
describe('decode a value accessed from a path', () => {
it('can decode a single object field', () => {
const decoder = valueAt(['a'], string());
expect(decoder.run({a: 'boots', b: 'cats'})).toEqual({ok: true, result: 'boots'});
Expand Down Expand Up @@ -573,7 +603,10 @@ describe('valueAt', () => {
});

describe('decode an optional field', () => {
const decoder = valueAt(['a', 'b', 'c'], oneOf(string(), constant(undefined)));
const decoder: Decoder<string | undefined> = valueAt(
['a', 'b', 'c'],
union(string(), constant(undefined))
);

it('fails when the path does not exist', () => {
const error = decoder.run({a: {x: 'cats'}});
Expand Down

0 comments on commit faaa15e

Please sign in to comment.