idx
Version:
Utility function for traversing properties on objects and arrays.
98 lines (96 loc) • 2.35 kB
JavaScript
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
;
// eslint-disable-line strict
jest.unmock('./idx');
var idx = require('./idx');
describe('idx', function () {
it('returns properties that exist', function () {
var a = {
b: {
c: 123
}
};
expect(idx(a, function (_) {
return _.b.c;
})).toEqual(123);
});
it('throws non-"property access" errors', function () {
var error = new Error('Expected error.');
var a = {};
Object.defineProperty(a, 'b', {
get: function get() {
throw error;
}
});
expect(function () {
return idx(a, function (_) {
return _.b.c;
});
}).toThrow(error);
});
it('throws a `TypeError` when calling non-methods', function () {
var a = {
b: 'I am a string'
};
expect(function () {
return idx(a, function (_) {
return _.b();
});
}).toThrow(new TypeError('_.b is not a function'));
});
it('returns null for intermediate null properties', function () {
var a = {
b: null
};
expect(idx(a, function (_) {
return _.b.c;
})).toEqual(null);
});
it('returns undefined for intermediate undefined properties', function () {
var a = {
b: undefined
};
expect(idx(a, function (_) {
return _.b.c;
})).toEqual(undefined);
});
it('returns undefined for intermediate undefined array indexes', function () {
var a = {
b: []
};
expect(idx(a, function (_) {
return _.b[0].c;
})).toEqual(undefined);
});
it('returns null for error in capital case', function () {
var error = new TypeError('b is NULL');
var a = {};
Object.defineProperty(a, 'b', {
get: function get() {
throw error;
}
});
expect(idx(a, function (_) {
return _.b.c;
})).toEqual(null);
});
it('returns undefined for error in capital case', function () {
var error = new TypeError('b is UNDEFINED');
var a = {};
Object.defineProperty(a, 'b', {
get: function get() {
throw error;
}
});
expect(idx(a, function (_) {
return _.b.c;
})).toEqual(undefined);
});
});