Skip to content

Commit

Permalink
fix: Optimize unit test
Browse files Browse the repository at this point in the history
  • Loading branch information
Romakita committed Mar 11, 2019
1 parent 808c90f commit 43021ef
Show file tree
Hide file tree
Showing 18 changed files with 1,524 additions and 1,278 deletions.
17 changes: 8 additions & 9 deletions .nycrc
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,18 @@
"extension": [
".ts"
],
"require": [
"ts-node/register"
],
"require": [],
"reporter": [
"lcov",
"text-summary"
"text-summary",
"html",
"lcov"
],
"clean": true,
"sourceMap": true,
"check-coverage": true,
"lines": 99,
"statements": 100,
"functions": 99,
"branches": 89,
"all": true,
"sourceMap": true,
"instrument": true
"branches": 85.17,
"all": true
}
12 changes: 7 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@
"semantic-release:dry-run": "semantic-release --dry-run",
"clean": "gulp clean:workspace",
"start": "ts-node -r tsconfig-paths/register -r source-map-support/register test/integration/app/app.ts",
"test": "npm run clean && npm run test:lint && npm run test:unit",
"test:unit": "cross-env NODE_ENV=test nyc --reporter=html --reporter=text mocha --recursive",
"test": "npm run clean && npm run test:lint && npm run test:coverage",
"test:unit": "cross-env NODE_ENV=test mocha",
"test:coverage": "cross-env NODE_ENV=test nyc mocha",
"test:lint": "tslint --project tsconfig.json -e integration",
"test:lint:fix": "tslint --project tsconfig.json --fix",
"travis:deploy-once": "travis-deploy-once",
Expand Down Expand Up @@ -64,8 +65,8 @@
"@types/json-schema": "^7.0.0",
"globby": "^9.0.0",
"reflect-metadata": "^0.1.12",
"ts-httpexceptions": "^3.0.2",
"ts-log-debug": "^4.0.1"
"ts-httpexceptions": "^4.0.0",
"ts-log-debug": "^5.0.1"
},
"devDependencies": {
"@typedproject/ts-doc": "^4.0.1",
Expand Down Expand Up @@ -128,6 +129,7 @@
"sinon-chai": "^3.0.0",
"socket.io": "^2.0.4",
"socket.io-client": "^2.1.0",
"source-map-support": "^0.5.10",
"supertest": "^3.0.0",
"swagger-ui-dist": "^3.13.6",
"travis-deploy-once": "^5.0.4",
Expand All @@ -145,4 +147,4 @@
"packages": "packages",
"test": "test"
}
}
}
12 changes: 9 additions & 3 deletions packages/common/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,10 @@
call-me-maybe "^1.0.1"
glob-to-regexp "^0.3.0"

"@types/json-schema@^6.0.0":
version "6.0.0"
resolved "https://registry.yarnpkg.com/@types/json-schema/-/json-schema-6.0.0.tgz#5842b43db9d199a2dabf6fe52b6d09200e8203bc"
"@types/json-schema@^6.0.1":
version "6.0.1"
resolved "https://registry.yarnpkg.com/@types/json-schema/-/json-schema-6.0.1.tgz#a761975746f1c1b2579c62e3a4b5e88f986f7e2e"
integrity sha512-vuL/tG01yKO//gmCmnV3OZhx2hs538t+7FpQq//sUV1sF6xiKi5V8F60dvAxe/HkC4+QaMCHqrm/akqlppTAkQ==

arr-diff@^4.0.0:
version "4.0.0"
Expand Down Expand Up @@ -816,6 +817,11 @@ tslib@^1.8.0:
version "1.9.0"
resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.9.0.tgz#e37a86fda8cbbaf23a057f473c9f4dc64e5fc2e8"

tslib@^1.9.0:
version "1.9.3"
resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.9.3.tgz#d7e4dd79245d85428c4d7e4822a79917954ca286"
integrity sha512-4krF8scpejhaOgqzBEcGM7yDIEfi0/8+8zDRZhNZZ2kjmHJ4hv3zCbQWxoJGz1iw5U0Jl0nma13xzHXcncMavQ==

union-value@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/union-value/-/union-value-1.0.0.tgz#5c71c34cb5bad5dcebe3ea0cd08207ba5aa1aea4"
Expand Down
6 changes: 2 additions & 4 deletions packages/di/src/class/Provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,10 @@ export class Provider<T> implements IProvider<T> {

@NotEnumerable()
protected _type: ProviderType | any = ProviderType.PROVIDER;

protected _provide: RegistryKey;
@NotEnumerable()
private _store: Store;

protected _provide: RegistryKey;

constructor(provide: RegistryKey) {
this._provide = getClassOrSymbol(provide);
this._useClass = getClass(this._provide);
Expand Down Expand Up @@ -45,7 +43,7 @@ export class Provider<T> implements IProvider<T> {
* @returns {Type<T>}
*/
get useClass(): Type<T> {
return this._useClass || this._provide;
return this._useClass;
}

/**
Expand Down
2 changes: 1 addition & 1 deletion packages/di/src/class/Providers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export class Providers extends Registry<Provider<any>, IProvider<any>> {
* @param options
* @returns {Registry<Provider<any>, IProvider<any>>}
*/
createRegistry(type: string, model: Type<Provider<any>>, options: Partial<RegistrySettings> = {}): TypedProvidersRegistry {
createRegistry(type: string, model: Type<Provider<any>>, options: Partial<RegistrySettings>): TypedProvidersRegistry {
const registry = new Registry<Provider<any>, IProvider<any>>(model, {
onCreate: this.set.bind(this)
});
Expand Down
46 changes: 46 additions & 0 deletions packages/mongoose/src/MongooseModule.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import {AfterRoutesInit, Constant, ExpressApplication, OnInit, Service} from "@tsed/common";
import * as Mongoose from "mongoose";
import {MDBConnection} from "./interfaces";
import {ValidationErrorMiddleware} from "./middlewares/ValidationErrorMiddleware";
import {MongooseService} from "./services/MongooseService";

@Service()
export class MongooseModule implements OnInit, AfterRoutesInit {
@Constant("mongoose.url")
private url: string;

@Constant("mongoose.connectionOptions")
private connectionOptions: Mongoose.ConnectionOptions;

@Constant("mongoose.urls")
private urls: {[key: string]: MDBConnection};

/**
*
* @type {Map<any, any>}
* @private
*/
private _instances: Map<string, Mongoose.Mongoose> = new Map();

constructor(@ExpressApplication private expressApp: ExpressApplication, private mongooseService: MongooseService) {}

$onInit(): Promise<any> | void {
const promises: Promise<Mongoose.Mongoose>[] = [];

if (this.url) {
promises.push(this.mongooseService.connect("default", this.url, this.connectionOptions || {}));
}

if (this.urls) {
Object.keys(this.urls).forEach((key: string) => {
promises.push(this.mongooseService.connect(key, this.urls[key].url, this.urls[key].connectionOptions || {}));
});
}

return Promise.all(promises);
}

$afterRoutesInit(): void {
this.expressApp.use(ValidationErrorMiddleware as any);
}
}
1 change: 1 addition & 0 deletions packages/mongoose/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,6 @@ declare module "@tsed/common" {
export * from "./interfaces";
export * from "./registries/MongooseModelRegistry";
export * from "./services/MongooseService";
export * from "./MongooseModule";
export * from "./utils";
export * from "./decorators";
3 changes: 2 additions & 1 deletion packages/mongoose/src/registries/MongooseModelRegistry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@
*/
import {GlobalProviders, Provider, TypedProvidersRegistry} from "@tsed/common";

export const PROVIDER_TYPE_MONGOOSE_MODEL = "mongooseModel";
// tslint:disable-next-line: variable-name
export const MongooseModelRegistry: TypedProvidersRegistry = GlobalProviders.createRegistry("mongooseModel", Provider, {
export const MongooseModelRegistry: TypedProvidersRegistry = GlobalProviders.createRegistry(PROVIDER_TYPE_MONGOOSE_MODEL, Provider, {
injectable: true,
buildable: false
});
Expand Down
56 changes: 4 additions & 52 deletions packages/mongoose/src/services/MongooseService.ts
Original file line number Diff line number Diff line change
@@ -1,66 +1,21 @@
import {AfterRoutesInit, Constant, ExpressApplication, OnInit, Service} from "@tsed/common";
import {Service} from "@tsed/common";
import * as Mongoose from "mongoose";
import {$log} from "ts-log-debug";
import {MDBConnection} from "../interfaces/MDBConnection";
import {ValidationErrorMiddleware} from "../middlewares/ValidationErrorMiddleware";

@Service()
export class MongooseService implements OnInit, AfterRoutesInit {
@Constant("mongoose.url")
private url: string;

@Constant("mongoose.connectionOptions")
private connectionOptions: Mongoose.ConnectionOptions;

@Constant("mongoose.urls")
private urls: {[key: string]: MDBConnection};

export class MongooseService {
/**
*
* @type {Map<any, any>}
* @private
*/
private _instances: Map<string, Mongoose.Mongoose> = new Map();

constructor(@ExpressApplication private expressApp: ExpressApplication) {}

$onInit(): Promise<any> | void {
const promises: Promise<Mongoose.Mongoose>[] = [];

if (this.url) {
promises.push(
this.connect(
"default",
this.url,
this.connectionOptions || {}
)
);
}

if (this.urls) {
Object.keys(this.urls).forEach((key: string) => {
promises.push(
this.connect(
key,
this.urls[key].url,
this.urls[key].connectionOptions
)
);
});
}

return Promise.all(promises);
}

$afterRoutesInit(): void {
this.expressApp.use(ValidationErrorMiddleware as any);
}

/**
*
* @returns {Promise<"mongoose".Connection>}
*/
async connect(id: string, url: string, connectionOptions: Mongoose.ConnectionOptions = {}): Promise<any> {
async connect(id: string, url: string, connectionOptions: Mongoose.ConnectionOptions): Promise<any> {
if (this.has(id)) {
return await this.get(id)!;
}
Expand All @@ -70,10 +25,7 @@ export class MongooseService implements OnInit, AfterRoutesInit {
$log.debug(`options: ${JSON.stringify(connectionOptions)}`);

try {
const mongoose = await Mongoose.connect(
url,
connectionOptions
);
const mongoose = await Mongoose.connect(url, connectionOptions);
this._instances.set(id, mongoose);

return mongoose;
Expand Down
87 changes: 87 additions & 0 deletions packages/mongoose/test/MongooseModule.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import {ServerSettingsService} from "@tsed/common";
import {inject, TestContext} from "@tsed/testing";
import * as Sinon from "sinon";
import {MongooseModule} from "../src";

describe("MongooseModule", () => {
describe("$onInit()", () => {
describe("when url is given", () => {
before(
inject([MongooseModule, ServerSettingsService], (mongooseModule: MongooseModule, serverSetttings: ServerSettingsService) => {
this.mongooseModule = mongooseModule;

serverSetttings.set("mongoose", {
url: "mongodb://test",
connectionOptions: {options: "options"}
});

this.connectStub = Sinon.stub(this.mongooseModule.mongooseService, "connect").resolves("test" as any);

return (this.result = mongooseModule.$onInit());
})
);

after(
inject([ServerSettingsService], (serverSetttings: ServerSettingsService) => {
serverSetttings.set("mongoose", {
url: undefined,
connectionOptions: undefined,
urls: undefined
});
this.connectStub.restore();
})
);
after(TestContext.reset);

it("should call the connect method", () => {
this.connectStub.should.have.been.calledWithExactly("default", "mongodb://test", {options: "options"});
});

it("should return a promise", () => {
this.result.should.eventually.deep.eq(["test"]);
});
});

describe("when a list of urls is given", () => {
before(
inject([MongooseModule, ServerSettingsService], (mongooseModule: MongooseModule, serverSetttings: ServerSettingsService) => {
this.mongooseModule = mongooseModule;

serverSetttings.set("mongoose", {
url: undefined,
connectionOptions: undefined,
urls: {
db1: {
url: "mongodb://test",
connectionOptions: {options: "options"}
}
}
});

this.connectStub = Sinon.stub(this.mongooseModule.mongooseService, "connect").resolves("test" as any);

return (this.result = mongooseModule.$onInit());
})
);

after(
inject([ServerSettingsService], (serverSetttings: ServerSettingsService) => {
serverSetttings.set("mongoose", {
url: undefined,
connectionOptions: undefined,
urls: undefined
});
this.connectStub.restore();
})
);

it("should call the connect method", () => {
this.connectStub.should.have.been.calledWithExactly("db1", "mongodb://test", {options: "options"});
});

it("should return a promise", () => {
return this.result.should.eventually.deep.eq(["test"]);
});
});
});
});
Loading

0 comments on commit 43021ef

Please sign in to comment.