Skip to content

Commit

Permalink
feat(controllers): Add tests for all patch methods
Browse files Browse the repository at this point in the history
  • Loading branch information
zakhenry committed Jul 18, 2016
1 parent 5b9f9b6 commit a1150fc
Show file tree
Hide file tree
Showing 6 changed files with 159 additions and 4 deletions.
34 changes: 34 additions & 0 deletions src/browser/stores/http.store.spec.ts
Expand Up @@ -130,6 +130,40 @@ describe('Http store', () => {

})));

it('Checks if a single model exists with http', async(inject([TestHttpStore, MockBackend], (s: TestHttpStore, b: MockBackend) => {

let connection: MockConnection;
b.connections.subscribe((c: MockConnection) => connection = c);

const model = new TestModel({id: 321});

const testPromise = s.hasOne(model)
.then((res) => {

expect(res)
.toBe(true);

// make next request for failure, using 404 not found this time
const promise = s.hasOne(model);

connection.mockRespond(new Response(new ResponseOptions({
status: 404,
})));

return promise;

}).then((res) => {
expect(res).toBe(false);
});

connection.mockRespond(new Response(new ResponseOptions({
status: 204,
})));

return testPromise;

})));

it('Deletes a single model with http', async(inject([TestHttpStore, MockBackend], (s: TestHttpStore, b: MockBackend) => {

let connection: MockConnection;
Expand Down
9 changes: 9 additions & 0 deletions src/common/models/collection.spec.ts
Expand Up @@ -55,4 +55,13 @@ describe('Collection', () => {
.toThrowError(`Item with id [3] not in collection`);
});

it('can check if an entity is present in the collection', () => {

expect(collection.contains(data[1]))
.toBe(true);
expect(collection.contains(new BasicModel({id: 10})))
.toBe(false);

});

});
10 changes: 10 additions & 0 deletions src/common/stores/store.spec.ts
Expand Up @@ -12,6 +12,7 @@ import {
import { ValidationException } from '../../server/exeptions/exceptions';
import { Primary } from '../models/types/primary.decorator';
import Spy = jasmine.Spy;
import { Collection } from '../models/collection';

@Injectable()
class StubService {
Expand Down Expand Up @@ -187,6 +188,10 @@ describe('Mock Store', () => {
.then((ship) => {
expect(shipRef)
.toEqual(ship);
return c.shipStore.findMany();
})
.then((allModels:Collection<Ship>) => {
expect(allModels.findById(1234)).toEqual(shipRef);
});

})));
Expand All @@ -203,6 +208,11 @@ describe('Mock Store', () => {
.then((ship: Ship) => {
expect(ship instanceof Ship)
.toBe(true);

return c.shipStore.findMany();
})
.then((allModels:Collection<Ship>) => {
expect(() => allModels.findById(1234)).toThrowError('Item with id [1234] not in collection');
});

})));
Expand Down
82 changes: 81 additions & 1 deletion src/server/controllers/resource.controller.spec.ts
Expand Up @@ -16,6 +16,7 @@ import { Collection } from '../../common/models/collection';
import { EventEmitter } from 'events';
import { IncomingMessage } from 'http';
import { Primary } from '../../common/models/types/primary.decorator';
import * as _ from 'lodash';

class Fruit extends AbstractModel {
@Primary()
Expand Down Expand Up @@ -124,7 +125,44 @@ describe('Resource Controller', () => {
return methodInfo.callStackHandler(request, response)
.then((finalResponse) => {

console.log(finalResponse);
expect(finalResponse.body instanceof Fruit)
.toBe(true);
expect(finalResponse.body.getIdentifier())
.toBe(123);

});

});

})));

it('Registers a route to patch an entity', async(inject([TestController, Server],
(c: TestController, s: Server) => {

c.registerRoutes(s);

const methodInfo = s.configuredRoutes.find((r: RouteConfig) => r.methodName == 'patchOne');

expect(methodInfo)
.toBeDefined(`method info should exist for 'patchOne'`);

let emitter = new EventEmitter();

(emitter as any).setEncoding = (): any => null;

let request = new Request(emitter as IncomingMessage);
let response = new Response();

return (c as any).modelStore.findOne(123)
.then((fixture: Fruit) => {

process.nextTick(() => {
emitter.emit('data', JSON.stringify(fixture));
emitter.emit('end');
});

return methodInfo.callStackHandler(request, response)
.then((finalResponse) => {

expect(finalResponse.body instanceof Fruit)
.toBe(true);
Expand All @@ -137,6 +175,48 @@ describe('Resource Controller', () => {

})));

it('Throws exception when patch is attempted on entity that does not exist', async(inject([TestController, Server],
(c: TestController, s: Server) => {

c.registerRoutes(s);

const methodInfo = s.configuredRoutes.find((r: RouteConfig) => r.methodName == 'patchOne');

expect(methodInfo)
.toBeDefined(`method info should exist for 'patchOne'`);

let emitter = new EventEmitter();

(emitter as any).setEncoding = (): any => null;

let request = new Request(emitter as IncomingMessage);
let response = new Response();

return (c as any).modelStore.findOne(123)
.then((fixture: Fruit) => {

fixture = _.clone(fixture);
fixture.fruitId = 999; //not in store

const hasOneSpy = spyOn((c as any).modelStore, 'hasOne').and.callThrough();

process.nextTick(() => {
emitter.emit('data', JSON.stringify(fixture));
emitter.emit('end');
});

return methodInfo.callStackHandler(request, response)
.then((res:Response) => {

expect(hasOneSpy).toHaveBeenCalledWith(fixture);
expect(res.body.message).toEqual('NotFoundException: Model with id [999] does not exist');

});

});

})));

it('Registers a route to retrieve many entities', async(inject([TestController, Server],
(c: TestController, s: Server) => {

Expand Down
24 changes: 23 additions & 1 deletion src/server/stores/db.store.spec.ts
Expand Up @@ -122,7 +122,6 @@ describe('Database Store', () => {

})));


it('deletes a single entity from the orm', async(inject([TestDatabaseStore, Database], (store: TestDatabaseStore, db: Database) => {

(db as any).connection = dbConnectionSpy;
Expand Down Expand Up @@ -198,6 +197,29 @@ describe('Database Store', () => {

})));

it('checks if entity exists in the orm', async(inject([TestDatabaseStore, Database], (store: TestDatabaseStore, db: Database) => {

(db as any).connection = dbConnectionSpy;

const testModelFixture = new TestModel({id: 10});

repositorySpy.findOneById.and.returnValue(Promise.resolve(testModelFixture));

return store.hasOne(testModelFixture)
.then((res) => {
expect(res)
.toBe(true);
repositorySpy.findOneById.and.returnValue(Promise.reject(new Error('not found')));

return store.hasOne(testModelFixture);
})
.then((res) => {
expect(res)
.toBe(false);
});

})));

});


4 changes: 2 additions & 2 deletions src/server/stores/db.store.ts
Expand Up @@ -6,7 +6,7 @@ import { Injectable, Injector } from '@angular/core';
import { AbstractModel, ModelStatic, identifier } from '../../common/models/model';
import { Database } from '../services/database.service';
import { Logger } from '../../common/services/logger.service';
import { AbstractStore } from '../../common/stores/store';
import { AbstractStore, Query } from '../../common/stores/store';
import { Collection } from '../../common/models/collection';
import { NotFoundException } from '../exeptions/exceptions';
import { Repository, Connection } from 'typeorm';
Expand Down Expand Up @@ -72,7 +72,7 @@ export abstract class DatabaseStore<T extends AbstractModel> extends AbstractSto
/**
* @inheritdoc
*/
public findMany(query?: any): Promise<Collection<T>> {
public findMany(query?: Query): Promise<Collection<T>> {
return this.getRepository()
.then((repo) => repo.find({
//@todo define query and restrict count with pagination
Expand Down

0 comments on commit a1150fc

Please sign in to comment.