all files / src/__tests__/ read.spec.js

100% Statements 40/40
100% Branches 4/4
100% Functions 10/10
100% Lines 37/37
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69                                                                  
import expect from 'expect';
import read from '../read';
 
describe('read', () => {
  it('should get simple values', () => {
    expect(read('foo', {foo: 'bar'})).toBe('bar');
    expect(read('foo', {foo: 7})).toBe(7);
    expect(read('bar', {bar: true})).toBe(true);
  });
 
  it('should get arbitrarily deep dotted values', () => {
    const data = {
      foo: {
        bar: {
          baz: 42
        }
      }
    };
    expect(read('foo', data)).toBe(data.foo);
    expect(read('foo.bar', data)).toBe(data.foo.bar);
    expect(read('foo.bar.baz', data)).toBe(42);
  });
 
  it('should return undefined if structure is incomplete', () => {
    const data = {
      foo: {}
    };
    expect(read('foo', data)).toBe(data.foo);
    expect(read('foo.bar', data)).toBe(undefined);
    expect(read('foo.bar.baz', data)).toBe(undefined);
  });
 
  it('should throw an error when array syntax is broken', () => {
    expect(() => {
      read('foo[dog', {});
    }).toThrow(/found/);
  });
 
  it('should get simple array values', () => {
    const data = {
      cat: ['foo', 'bar', 'baz']
    };
    expect(read('cat[0]', data)).toBe('foo');
    expect(read('cat[1]', data)).toBe('bar');
    expect(read('cat[2]', data)).toBe('baz');
  });
 
  it('should get return undefined when array is not there', () => {
    const data = {
      cat: undefined
    };
    expect(read('cat[0]', data)).toBe(undefined);
  });
 
  it('should get complex array values', () => {
    const data = {
      rat: {
        cat: [{name: 'foo'}, {name: 'bar'}, {name: 'baz'}]
      }
    };
    expect(read('rat.cat[0].name', data)).toBe('foo');
    expect(read('rat.cat[0][name]', data)).toBe('foo');
    expect(read('rat.cat[1].name', data)).toBe('bar');
    expect(read('rat.cat[1][name]', data)).toBe('bar');
    expect(read('rat.cat[2].name', data)).toBe('baz');
    expect(read('rat.cat[2][name]', data)).toBe('baz');
  });
});