CodeX

Everything connected with Tech & Code. Follow to join our 1M+ monthly readers

Follow publication

A study of Test Driven Development and Functional Programming in TypeScript

Adam Fanello
CodeX
Published in
10 min readJun 6, 2022

Photo by Dmitry Ratushny on Unsplash

Introduction

What really is Test Driven Development?

What is Functional Programming?

So… TDD?

So… FP?

function a() {
}

function fakeA() {
}

function b() {
}

function fakeB() {
}

export function moduleFactory(
otherModuleDependency = otherModuleFactory(),
) {
return {a, b};
}

export function fakeModuleFactory() {
return {a: fakeA, b: fakeB};
}
import UserRepository from "user.repository";

export default (repo = UserRepository()) => {
return {
a: () => {
},
b: () => {
},
};
}

So… OOP?

import { isUserSignUpRequest, UserSignUpRequest, UserSignUpResponse } from "domain/models";
import { newUserFactory } from "domain/logic/user";
import { assertValidInput } from "utils/assertions";

// Optionally use DI magic to gain performance of singletons:
// @Injectable()
export class UserSignUpUseCase {
// Dependencies defaulted - tests can provide mocks or fakes
constructor(
auth = new AuthService(),
userRepo = new UserRepository(),
) {
}

async process(request: UserSignUpRequest): Promise<UserSignUpResponse> {
this.validateRequest(request);
const user = newUserFactory(request);
await this.userRepo.put(user);
return {user};
}

private validateRequest(request: UserSignUpRequest): void {
this.auth.assertIsNotAuthenticated();
assertValidInput(request, isUserSignUpRequest);
}
}

Rules to Follow?

File structure

 .
└── src
├── domain
│ ├── logic # domain logic functions & OO classes
│ │ └── user.logic.ts
│ └── models
│ ├── index.ts
│ └── user.ts
├── handlers
│ └── user-sign-up.lambda.ts
├── external
│ ├── dynamodb.service.ts
│ └── repositories
│ └── user.repository.ts
└── use-cases
└── user
├── user-sign-up.test.ts
└── user-sign-up.ts

Conclusion

CodeX
CodeX

Published in CodeX

Everything connected with Tech & Code. Follow to join our 1M+ monthly readers

Adam Fanello
Adam Fanello

Written by Adam Fanello

Consulting Software Engineer and AWS Solutions Architect with over 34 years of experience. Specializing in AWS serverless application development and IoT.

Responses (4)

Write a response