From 08e1c076739867a9e73a707adc66767a7e8525d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Loren=20=F0=9F=A4=93?= Date: Mon, 13 Sep 2021 00:03:17 -0400 Subject: [PATCH] Add test case for #79 --- src/__tests__/cache.test.js | 16 +++++++++++++++- src/__tests__/datasource.test.js | 8 +++++++- src/cache.js | 2 +- 3 files changed, 23 insertions(+), 3 deletions(-) diff --git a/src/__tests__/cache.test.js b/src/__tests__/cache.test.js index 8054db3..7afa079 100644 --- a/src/__tests__/cache.test.js +++ b/src/__tests__/cache.test.js @@ -7,7 +7,8 @@ import { createCachingMethods, idToString, isValidObjectIdString, - prepFields + prepFields, + getNestedValue } from '../cache' import { log } from '../helpers' @@ -313,3 +314,16 @@ describe('isValidObjectIdString', () => { expect(isValidObjectIdString(hexId)).toBe(true) }) }) + +describe('getNestedValue', () => { + it('works', () => { + const obj = { + nested: { foo: 'bar', fooB: '', fooC: null, fooE: { inner: true } } + } + expect(getNestedValue(obj, 'nested.foo')).toEqual('bar') + expect(getNestedValue(obj, 'nested.fooB')).toEqual('') + expect(getNestedValue(obj, 'nested.fooC')).toEqual(null) + expect(getNestedValue(obj, 'nested.fooD')).toBeUndefined() + expect(getNestedValue(obj, 'nested.fooE.inner')).toBe(true) + }) +}) diff --git a/src/__tests__/datasource.test.js b/src/__tests__/datasource.test.js index 4ccc995..14b1c76 100644 --- a/src/__tests__/datasource.test.js +++ b/src/__tests__/datasource.test.js @@ -64,7 +64,7 @@ describe('Mongoose', () => { nestedBob = await userCollection.findOneAndReplace( { name: 'Bob' }, - { name: 'Bob', nested: [{ _id: objectID }] }, + { name: 'Bob', nested: { _id: objectID, field1: 'value1', field2: '' } }, { new: true, upsert: true } ) }) @@ -128,5 +128,11 @@ describe('Mongoose', () => { expect(user).toBeDefined() expect(user.name).toBe('Bob') + + const res1 = await users.findByFields({ 'nested.field1': 'value1' }) + const res2 = await users.findByFields({ 'nested.field2': 'value1' }) + + expect(res1[0].name).toBe('Bob') + expect(res2[0]).toBeUndefined() }) }) diff --git a/src/cache.js b/src/cache.js index 5430f36..d36fdc6 100644 --- a/src/cache.js +++ b/src/cache.js @@ -46,7 +46,7 @@ export function prepFields(fields) { // getNestedValue({ nested: { foo: 'bar' } }, 'nested.foo') // => 'bar' -function getNestedValue(object, string) { +export function getNestedValue(object, string) { string = string.replace(/\[(\w+)\]/g, '.$1') // convert indexes to properties string = string.replace(/^\./, '') // strip a leading dot var a = string.split('.')