Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
node_modules
*.log
.DS_Store
/coverage
8 changes: 4 additions & 4 deletions TypeScript/1-Repository.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
// Entity DAO

type RawUser = { id: number; name: string };
export type RawUser = { id: number; name: string };

class UserDAO {
export class UserDAO {
constructor(public options: { fake: true }) {}

getById(id: number): Promise<RawUser> {
Expand All @@ -13,13 +13,13 @@ class UserDAO {

// Domain Entity

class User {
export class User {
constructor(public id: number, public name: string) {}
}

// Repository

class UserRepository {
export class UserRepository {
constructor(private dao: UserDAO) {}

async findById(id: number): Promise<User> {
Expand Down
41 changes: 41 additions & 0 deletions TypeScript/__tests__/1-Repository.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { UserDAO, UserRepository, User } from '../1-Repository';

describe('UserDAO', () => {
it('should return RawUser when fake=true', async () => {
const dao = new UserDAO({ fake: true });
const raw = await dao.getById(42);
expect(raw).toEqual({ id: 42, name: 'Marcus Aurelius' });
});

it('should throw an error when fake=false', () => {
const dao = new UserDAO({ fake: false as any });
expect(() => dao.getById(1)).toThrow('Not a fake');
});
});

describe('UserRepository', () => {
it('should return a User instance for valid data', async () => {
const dao = new UserDAO({ fake: true });
const repo = new UserRepository(dao);
const user = await repo.findById(7);
expect(user).toBeInstanceOf(User);
expect(user).toMatchObject({ id: 7, name: 'Marcus Aurelius' });
});

it('should propagate errors from DAO when it throws', async () => {
const throwingDao = {
getById: jest.fn().mockRejectedValue(new Error('Not a fake'))
} as unknown as UserDAO;
const repo = new UserRepository(throwingDao);
await expect(repo.findById(3)).rejects.toThrow('Not a fake');
});

it('should throw "Record not found" if DAO returns null/undefined', async () => {
const nullDao = {
getById: jest.fn().mockResolvedValue(null)
} as unknown as UserDAO;
const repo = new UserRepository(nullDao);
await expect(repo.findById(5))
.rejects.toThrow('Record not found: User(5)');
});
});
7 changes: 7 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
roots: ['<rootDir>/TypeScript'],
testMatch: ['**/?(*.)+(spec|test).[t]s'],
moduleFileExtensions: ['ts', 'js', 'json', 'node'],
};
Loading