From fde6d6a6f7b8330f5768dfaaee06c45c37f0501b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miroslav=20Bajto=C5=A1?= Date: Thu, 18 Jul 2019 16:34:27 +0200 Subject: [PATCH] feat: add DataSource.reset() API MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When writing tests, for performance reasons we often want to reuse the same data-source instance for many tests suites. At the same time, we want to keep such test suites independent and allow them to reuse the same model name for different model classes. Juggler does support redefinition of a model with the same name. This change is adding a new API called `dataSource.reset()` that allows tests to remove all old models before creating new ones (typically from a `before` hook). Signed-off-by: Miroslav Bajtoš --- lib/datasource.js | 10 ++++++++++ test/datasource.test.js | 28 ++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/lib/datasource.js b/lib/datasource.js index 29249b9d5..ed8359033 100644 --- a/lib/datasource.js +++ b/lib/datasource.js @@ -844,6 +844,16 @@ DataSource.prototype.deleteModelByName = function(modelName) { delete this.connector._models[modelName]; }; +/** + * Remove all models from the registry, but keep the connector instance + * (including the pool of database connections). + */ +DataSource.prototype.reset = function() { + for (const m in this.modelBuilder.models) { + this.deleteModelByName(m); + } +}; + /** * Mixin DataAccessObject methods. * diff --git a/test/datasource.test.js b/test/datasource.test.js index adb632820..3639ebe5d 100644 --- a/test/datasource.test.js +++ b/test/datasource.test.js @@ -517,6 +517,34 @@ describe('DataSource', function() { }); } }); + + describe('reset', () => { + it('removes all model definitions', () => { + const ds = new DataSource({connector: 'memory'}); + ds.define('Category'); + ds.define('Product'); + + Object.keys(ds.modelBuilder.definitions) + .should.deepEqual(['Category', 'Product']); + Object.keys(ds.modelBuilder.models) + .should.deepEqual(['Category', 'Product']); + Object.keys(ds.connector._models) + .should.deepEqual(['Category', 'Product']); + + ds.reset(); + + Object.keys(ds.modelBuilder.definitions).should.be.empty(); + Object.keys(ds.modelBuilder.models).should.be.empty(); + Object.keys(ds.connector._models).should.be.empty(); + }); + + it('preserves the connector instance', () => { + const ds = new DataSource({connector: 'memory'}); + const connector = ds.connector; + ds.reset(); + ds.connector.should.equal(connector); + }); + }); }); function givenMockConnector(props) {