I would like to be able to test my Nest service against an actual database. I understand that most unit tests should use a mock object, but it also, at times, makes sense to test against the database itself.
I have searched through SO and the GH issues for Nest, and am starting to reach the transitive closure of all answers. :-)
I am trying to work from https://github.com/nestjs/nest/issues/363#issuecomment-360105413. Following is my Unit test, which uses a custom provider to pass the repository to my service class.
describe("DepartmentService", () => {
const token = getRepositoryToken(Department);
let service: DepartmentService;
let repo: Repository<Department>;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
DepartmentService,
{
provide: token,
useClass: Repository
}
]
}).compile();
service = module.get<DepartmentService>(DepartmentService);
repo = module.get(token);
});
Everything compiles properly, TypeScript seems happy. However, when I try to execute create or save on my Repository instance, the underlying Repository appears to be undefined. Here's the stack backtrace:
TypeError: Cannot read property 'create' of undefined
at Repository.Object.<anonymous>.Repository.create (repository/Repository.ts:99:29)
at DepartmentService.<anonymous> (relational/department/department.service.ts:46:53)
at relational/department/department.service.ts:19:71
at Object.<anonymous>.__awaiter (relational/department/department.service.ts:15:12)
at DepartmentService.addDepartment (relational/department/department.service.ts:56:16)
at Object.<anonymous> (relational/department/test/department.service.spec.ts:46:35)
at relational/department/test/department.service.spec.ts:7:71
It appears that the EntityManager instance with the TypeORM Repository class is not being initialized; it is the undefined reference that this backtrace is complaining about.
How do I get the Repository and EntityManager to initialize properly?
thanks,
tom.
To initialize typeorm properly, you should just be able to import the TypeOrmModule in your test:
Test.createTestingModule({
imports: [
TypeOrmModule.forRoot({
type: 'mysql',
// ...
}),
TypeOrmModule.forFeature([Department])
]
I prefer not using #nestjs/testing for the sake of simplicity.
First of all, create a reusable helper:
/* src/utils/testing-helpers/createMemDB.js */
import { createConnection, EntitySchema } from 'typeorm'
type Entity = Function | string | EntitySchema<any>
export async function createMemDB(entities: Entity[]) {
return createConnection({
// name, // let TypeORM manage the connections
type: 'sqlite',
database: ':memory:',
entities,
dropSchema: true,
synchronize: true,
logging: false
})
}
Then, write test:
/* src/user/user.service.spec.ts */
import { Connection, Repository } from 'typeorm'
import { createMemDB } from '../utils/testing-helpers/createMemDB'
import UserService from './user.service'
import User from './user.entity'
describe('User Service', () => {
let db: Connection
let userService: UserService
let userRepository: Repository<User>
beforeAll(async () => {
db = await createMemDB([User])
userRepository = await db.getRepository(User)
userService = new UserService(userRepository) // <--- manually inject
})
afterAll(() => db.close())
it('should create a new user', async () => {
const username = 'HelloWorld'
const password = 'password'
const newUser = await userService.createUser({ username, password })
expect(newUser.id).toBeDefined()
const newUserInDB = await userRepository.findOne(newUser.id)
expect(newUserInDB.username).toBe(username)
})
})
Refer to https://github.com/typeorm/typeorm/issues/1267#issuecomment-483775861
Here's an update to the test that employs Kim Kern's suggestion.
describe("DepartmentService", () => {
let service: DepartmentService;
let repo: Repository<Department>;
let module: TestingModule;
beforeAll(async () => {
module = await Test.createTestingModule({
imports: [
TypeOrmModule.forRoot(),
TypeOrmModule.forFeature([Department])
],
providers: [DepartmentService]
}).compile();
service = module.get<DepartmentService>(DepartmentService);
repo = module.get<Repository<Department>>(getRepositoryToken(Department));
});
afterAll(async () => {
module.close();
});
it("should be defined", () => {
expect(service).toBeDefined();
});
// ...
}
I created a test orm configuration
// ../test/db.ts
import { TypeOrmModuleOptions } from '#nestjs/typeorm';
import { EntitySchema } from 'typeorm';
type Entity = Function | string | EntitySchema<any>;
export const createTestConfiguration = (
entities: Entity[],
): TypeOrmModuleOptions => ({
type: 'sqlite',
database: ':memory:',
entities,
dropSchema: true,
synchronize: true,
logging: false,
});
which I then utilize when setting up the tests
// books.service.test.ts
import { Test, TestingModule } from '#nestjs/testing';
import { HttpModule, HttpService } from '#nestjs/common';
import { TypeOrmModule, getRepositoryToken } from '#nestjs/typeorm';
import { Repository } from 'typeorm';
import { BooksService } from './books.service';
import { Book } from './book.entity';
import { createTestConfiguration } from '../../test/db';
describe('BooksService', () => {
let module: TestingModule;
let service: BooksService;
let httpService: HttpService;
let repository: Repository<Book>;
beforeAll(async () => {
module = await Test.createTestingModule({
imports: [
HttpModule,
TypeOrmModule.forRoot(createTestConfiguration([Book])),
TypeOrmModule.forFeature([Book]),
],
providers: [BooksService],
}).compile();
httpService = module.get<HttpService>(HttpService);
service = module.get<BooksService>(BooksService);
repository = module.get<Repository<Book>>(getRepositoryToken(Book));
});
afterAll(() => {
module.close();
});
it('should be defined', () => {
expect(service).toBeDefined();
});
This allows to query the repository after the tests and ensure that the correct data was inserted.
I usually import AppModule for database connection, and finally after tests are executed I close the connection:
let service: SampleService;
let connection: Connection;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
imports: [AppModule, TypeOrmModule.forFeature([SampleEntity])],
providers: [SampleService],
}).compile();
service = module.get<SampleService>(SampleService);
connection = await module.get(getConnectionToken());
});
afterEach(async () => {
await connection.close();
});
I used existing AppModule for testing:
import { INestApplication } from '#nestjs/common';
import { NestFactory } from '#nestjs/core';
import { AppModule } from '../../../app.module';
import { AuthService } from '../auth.service';
describe('AuthService', () => {
let app: INestApplication;
let service: AuthService;
beforeAll(async () => {
app = await NestFactory.create(AppModule);
service = app.get(AuthService);
});
afterAll(async () => {
await app.close();
});
it('AuthService should be defined', () => {
expect(service).toBeDefined();
});
describe('login', () => {
it('should login user', async () => {
const user = await service.login({ email: 'xxxzei#mail.ru', password: '12345678' });
expect(user.id).toBeDefined();
});
});
});
Also to add env variables in your configuration file or AppModule:
import { config as testConfig } from 'dotenv';
if (process.env.NODE_ENV === 'test') {
testConfig({ path: resolve('./.env') });
}
Related
I want to unit test my service. Inside my service I have a constructor that is:
contractService.ts:
export class ContractService {
private logger = new Logger("ContractService");
constructor(
#InjectModel(Contract)
private contractModel: typeof Contract
) {}
async getContracts(query: PaginationInterface): Promise<FetchContract> {
const { limit, page, skip } = paginationParseParams(query);
const { sortBy, direction } = sortParseParams(query, ColumnDetails);
const { count, rows } = await this.contractModel.findAndCountAll({
where: {},
offset: skip,
limit: limit,
order: [[sortBy, direction]],
});
const pages = Math.ceil(count / limit);
const meta = {
limit,
skip,
page,
count,
pages,
sortBy,
direction,
};
return { meta, data: rows };
}
}
My model looks like this: (Model is a class from sequelize-typescript)
export class Contract extends Model<Contract> {
....
}
So I want to create my unit test with jest. When I try to mock the contractModel, it does not find the method, eventhough I am trying to mock it.
const mockContractModel = () => ({
findAndCountAll: jest.fn(),
});
describe("ContractService", () => {
let contractService: ContractService;
let contractModel: Contract;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
ContractService,
{
provide: Contract,
useFactory: mockContractModel,
},
],
}).compile();
contractService = module.get<ContractService>(ContractService);
contractModel = module.get<Contract>(Contract);
});
it("should be defined", () => {
expect(contractService).toBeDefined();
});
describe("Get contracts", () => {
it("Should return all the contracts", async () => {
expect(contractModel.findAndCountAll).not.toHaveBeenCalled();
await contractService.getContracts(defaultPagination);
expect(contractModel.findAndCountAll).toHaveBeenCalled();
});
});
});
What is the right way to mock this contractModel?
Instead of using
{
provide: Contract,
useFactory: mockContractModel
}
You should be using
{
provide: getModelToken(Contract),
useFactory: mockContractModel
}
where getModelToken is imported from #nestjs/mongoose. This will get the correct DI token for Nest to know what you're mocking. For more examples, check this git repo
In this project, it uses NestJS along with TypeORM. For real API requests, CRUD operation is being operated on MySQL(which is using AWS RDS).
Now I am trying to use SQLite(In-Memory) to test API results.
I successfully implemented this in Unit Test, as the code below.
First, below is create-memory-db.ts, which returns a connection to in-memory SQLite database.
type Entity = Function | string | EntitySchema<any>;
export async function createMemoryDB(entities: Entity[]) {
return createConnection({
type: 'sqlite',
database: ':memory:',
entities,
logging: false,
synchronize: true,
});
}
And by using the exported function above, I successfully ran Unit test, like below.
describe('UserService Logic Test', () => {
let userService: UserService;
let connection: Connection;
let userRepository: Repository<User>;
beforeAll(async () => {
connection = await createMemoryDB([User]);
userRepository = await connection.getRepository(User);
userService = new UserService(userRepository);
});
afterAll(async () => {
await connection.close();
});
afterEach(async () => {
await userRepository.query('DELETE FROM users');
});
// testing codes.
});
I am trying to do the same thing on e2e tests. I tried below code.
// user.e2e-spec.ts
describe('UserController (e2e)', () => {
let userController: UserController;
let userService: UserService;
let userRepository: Repository<User>;
let connection: Connection;
let app: INestApplication;
const NAME = 'NAME';
const EMAIL = 'test#test.com';
const PASSWORD = '12345asbcd';
beforeAll(async () => {
connection = await createMemoryDB([User]);
userRepository = await connection.getRepository(User);
userService = new UserService(userRepository);
userController = new UserController(userService);
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [],
controllers: [UserController],
providers: [UserService],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
afterAll(async () => {
await connection.close();
});
afterEach(async () => {
// await userRepository.query('DELETE FROM users');
});
it('[POST] /user : Response is OK if conditions are right', () => {
const dto = new UserCreateDto();
dto.name = NAME;
dto.email = EMAIL;
dto.password = PASSWORD;
return request(app.getHttpServer())
.post('/user')
.send(JSON.stringify(dto))
.expect(HttpStatus.CREATED);
});
});
I cannot create UserModule since it doesn't have a constructor with Connection parameter.
The code itself has no compile error, but gets results below when e2e test is executed.
Nest can't resolve dependencies of the UserService (?). Please make sure that the argument UserRepository at index[0] is available in the RootTestModule context.
Potential solutions:
- If UserRepository is a provider, is it part of the current RootTestModule?
- If UserRepository is exported from a seperate #Module, is that module imported within RootTestModule?
#Module({
imports: [/* The module containing UserRepository */]
})
TypeError: Cannot read property 'getHttpServer' of undefined.
Any help would be greatly appreciated. Thanks :)
UPDATE : New error occured after trying below.
describe('UserController (e2e)', () => {
let userService: UserService;
let userRepository: Repository<User>;
let connection: Connection;
let app: INestApplication;
const NAME = 'NAME';
const EMAIL = 'test#test.com';
const PASSWORD = '12345asbcd';
beforeAll(async () => {
connection = await createMemoryDB([User]);
userRepository = await connection.getRepository(User);
userService = new UserService(userRepository);
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [UserModule],
})
.overrideProvider(UserService)
.useClass(userService)
.compile();
app = moduleFixture.createNestApplication();
await app.init();
});
afterAll(async () => {
await connection.close();
});
afterEach(async () => {
await userRepository.query('DELETE FROM users');
});
it('[POST] /user : Response is OK if conditions are right', async () => {
const dto = new UserCreateDto();
dto.name = NAME;
dto.email = EMAIL;
dto.password = PASSWORD;
const result = await request(app.getHttpServer())
.post('/user')
.send(JSON.stringify(dto))
.expect({ status: HttpStatus.CREATED });
});
});
I checked if query is working, and was able to see that it is using SQLite database as I wanted. But new error appeared in console.
TypeError: metatype is not a constructor.
TypeError: Cannot read property 'getHttpServer' of undefined.
Okay, I solved this issue by using TypeOrm.forRoot() inside the imports field of Test.createTestingModule. Below is how I did it.
describe('UserController (e2e)', () => {
let userService: UserService;
let userRepository: Repository<User>;
let app: INestApplication;
const NAME = 'NAME';
const EMAIL = 'test#test.com';
const PASSWORD = '12345asbcd';
beforeAll(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [
UserModule,
TypeOrmModule.forRoot({
type: 'sqlite',
database: ':memory:',
entities: [User],
logging: true,
synchronize: true,
}),
],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
userRepository = moduleFixture.get('UserRepository');
userService = new UserService(userRepository);
});
afterAll(async () => {
await app.close();
});
afterEach(async () => {
await userRepository.query('DELETE FROM users');
});
});
For those looking for setup e2e tests that hit endpoints and assert the response body, you can do something like this:
// app.module.ts
#Module({
imports: [
TypeOrmModule.forRootAsync({
useFactory: async (configService: ConfigService) => {
if (process.env.APPLICATION_ENV === 'test') {
return {
type: 'sqlite',
database: ':memory:',
entities: [Entity],
synchronize: true,
}
}
return {
// your default options
};
},
}),
]
})
I am trying to develop an application using NestJs as the backend framework. Currently I am writing some integration tests for the controllers.
This is my first project using typescript, I usually use Java/Spring but I wanted to learn and give nestJs a try.
I use different guards to access rest endpoints. In this case I have an AuthGuard and RolesGuard
To make the rest endpoint work I just add something like this in the TestingModuleBuilder:
.overrideGuard(AuthGuard())
.useValue({ canActivate: () => true })
The point is, is it possible to define or override this guards for each test to check that the request should fail if no guard or not allowed guard is defined?
My code for the test is the following one:
describe('AuthController integration tests', () => {
let userRepository: Repository<User>
let roleRepository: Repository<Role>
let app: INestApplication
beforeAll(async () => {
const module = await Test.createTestingModule({
imports: [
AuthModule,
TypeOrmModule.forRoot(typeOrmConfigTest),
PassportModule.register({ defaultStrategy: 'jwt' }),
JwtModule.register({
secret: jwtConfig.secret,
signOptions: {
expiresIn: jwtConfig.expiresIn
}
})
]
})
.overrideGuard(AuthGuard())
.useValue({ canActivate: () => true })
.overrideGuard(RolesGuard)
.useValue({ canActivate: () => true })
.compile()
app = module.createNestApplication()
await app.init()
userRepository = module.get('UserRepository')
roleRepository = module.get('RoleRepository')
const initializeDb = async () => {
const roles = roleRepository.create([
{ name: RoleName.ADMIN },
{ name: RoleName.TEACHER },
{ name: RoleName.STUDENT }
])
await roleRepository.save(roles)
}
await initializeDb()
})
afterAll(async () => {
await roleRepository.query(`DELETE FROM roles;`)
await app.close()
})
afterEach(async () => {
await userRepository.query(`DELETE FROM users;`)
})
describe('users/roles (GET)', () => {
it('should retrieve all available roles', async () => {
const { body } = await request(app.getHttpServer())
.get('/users/roles')
.set('accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200)
expect(body).toEqual(
expect.arrayContaining([
{
id: expect.any(String),
name: RoleName.STUDENT
},
{
id: expect.any(String),
name: RoleName.TEACHER
},
{
id: expect.any(String),
name: RoleName.ADMIN
}
])
)
})
})
It's not immediately possibly with the current implementation, but if you save the guard mock as a jest mock it should be possible. Something like this
describe('Controller Integration Testing', () => {
let app: INestApplication;
const canActivate = jest.fn(() => true);
beforeEach(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
})
.overrideGuard(TestGuard)
.useValue({ canActivate })
.compile();
app = moduleFixture.createNestApplication();
await app.init();
});
it('/ (GET)', () => {
return request(app.getHttpServer())
.get('/')
.expect(200)
.expect('Hello World!');
});
it('/ (GET) Fail guard', () => {
canActivate.mockReturnValueOnce(false);
return request(app.getHttpServer())
.get('/')
.expect(403);
});
});
This is rather a stylistic question. I'm using Pino in some of my Javascript/Typescript microservices. As they're running on AWS I'd like to propagate the RequestId.
When one of my functions is invoked, I'm creating a new child logger like this:
const parentLogger = pino(pinoDefaultConfig)
function createLogger(context) {
return parentLogger.child({
...context,
})
}
function createLoggerForAwsLambda(awsContext) {
const context = {
requestId: awsContext.awsRequestId,
}
return createLogger(context)
}
I'm then passing down the logger instance to all methods. That said, (... , logger) is in almost every method signature which is not too nice. Moreover, I need to provide a logger in my tests.
How do you do it? Is there a better way?
you should implement some sort of Dependency Injection and include your logger there.
if your using microservices and maybe write lambdas in a functional approach, you can handle it by separating the initialization responsibility in a fashion like this:
import { SomeAwsEvent } from 'aws-lambda';
import pino from 'pino';
const createLogger = (event: SomeAwsEvent) => {
return pino().child({
requestId: event.requestContext.requestId
})
}
const SomeUtil = (logger: pinno.Logger) => () => {
logger.info('SomeUtil: said "hi"');
}
const init(event: SomeAwsEvent) => {
const logger = createLogger(event);
someUtil = SomeUtil(logger);
return {
logger,
someUtil
}
}
export const handler = (event: SomeAwsEvent) => {
const { someUtil } = init(event);
someUtil();
...
}
The simplest way is to use some DI library helper to tackle this
import { createContainer } from "iti"
interface Logger {
info: (msg: string) => void
}
class ConsoleLogger implements Logger {
info(msg: string): void {
console.log("[Console]:", msg)
}
}
class PinoLogger implements Logger {
info(msg: string): void {
console.log("[Pino]:", msg)
}
}
interface UserData {
name: string
}
class AuthService {
async getUserData(): Promise<UserData> {
return { name: "Big Lebowski" }
}
}
class User {
constructor(private data: UserData) {}
name = () => this.data.name
}
class PaymentService {
constructor(private readonly logger: Logger, private readonly user: User) {}
sendMoney() {
this.logger.info(`Sending monery to the: ${this.user.name()} `)
return true
}
}
export async function runMyApp() {
const root = createContainer()
.add({
logger: () =>
process.env.NODE_ENV === "production"
? new PinoLogger()
: new ConsoleLogger(),
})
.add({ auth: new AuthService() })
.add((ctx) => ({
user: async () => new User(await ctx.auth.getUserData()),
}))
.add((ctx) => ({
paymentService: async () =>
new PaymentService(ctx.logger, await ctx.user),
}))
const ps = await root.items.paymentService
ps.sendMoney()
}
console.log(" ---- My App START \n\n")
runMyApp().then(() => {
console.log("\n\n ---- My App END")
})
it is easy to write tests too:
import { instance, mock, reset, resetCalls, verify, when } from "ts-mockito"
import { PaymentService } from "./payment-service"
import type { Logger } from "./logger"
const mockedLogger = mock<Logger>()
when(mockedLogger.info).thenReturn(() => null)
describe("Payment service: ", () => {
beforeEach(() => {
resetCalls(mockedLogger)
// reset(mockedLogger)
})
it("should call logger info when sending money", () => {
const paymentService = new PaymentService(instance(mockedLogger))
expect(paymentService.sendMoney()).toBe(true)
})
})
I would not use the requestId as part of the context of the logger, but use it as the payload of the logger, like logger.info({ requestId }, myLogMessage). This was you can have a simple function create a child logger that you can use for the entire module.
I'm trying to write my first Angular 6 test. I have a component which returns a list of Companies from a service.
It looks like this:
Template
<div *ngFor="let company of this.companies">
<h4 id="company-{{company.id}}>{{company.name}}</h4>
</div>
Component.ts
import { ApiService } from '../service/api.service';
ngOnInit(): void {
this.companies = this.apiService.getCompanies();
}
Service
import { COMPANYLIST } from '../companyList';
companyList = COMPANYLIST;
public getCompanies(): Company[] {
return this.companyList;
}
I would like to test that I can see the list of Companies in the component. In my spec.ts I have tried to add a mocked apiService as per https://angular.io/guide/testing#component-with-a-dependency with no luck.
I'm guessing the test should look something like this, but I am having issues actually injecting the mocked service into this test.
it("should show the list of Companies", () => {
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector("company-" + this.company.id).textContent).toContain("Mock Company");
});
The strategy is to inject a place holder object for your service. In the test get a reference to that place holder object and then add fake functionality to it that will be called when testing the component.
Example (I omitted code that does not illustrate the point I am trying to make)
import { ApiService } from '../service/api.service';
describe('CompaniesComponent Tests', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [CompaniesComponent],
providers: [
{ provide: ApiService, useValue: {} }
]
}).compileComponents();
TestBed.compileComponents();
fixture = TestBed.createComponent(CompaniesComponent);
comp = fixture.componentInstance;
});
it("should show the list of Companies", () => {
// get service and fake a returned company list
const apiService = TestBed.get(ApiService) as ApiService;
apiService.getCompanies = () => ['Mock Company'];
// you probably need to call ngOnInit on your component so it retrieves the companies from the api service
comp.ngOnInit();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector("company-" + this.company.id).textContent).toContain("Mock Company");
});
You can mock your service :
export class MockCompanyService {
getCompanies: Spy;
constructor(config) {
this.getCompanies = jasmine.createSpy('getCompanies').and.callFake(() => config.companies);
}
}
In your test, you will give companies to you mock so when your function is called, you will have your companies displayed.:
describe('CompanyComponent', () => {
let component: CompanyComponent;
let fixture: ComponentFixture<CompanyComponent>;
let element;
const mockCompanies = [
...
];
beforeEach(async(() => {
return TestBed
.configureTestingModule({
declarations: [
CompanyComponent
],
imports: [],
providers: [
{
provide: ComponentFixtureAutoDetect,
useValue: true
}
]
})
.overrideComponent(CompanyComponent, {
set: {
providers: [
{provide: CompanyService, useValue: new MockCompanyService(mockCompanies)}
]
}
})
.compileComponents()
.then(() => {
fixture = TestBed.createComponent(CompanyComponent);
component = fixture.debugElement.componentInstance;
element = fixture.debugElement.nativeElement;
});
}));
it('should create', () => {
expect(component).toBeTruthy();
});
it('...', () => {
});
});
in your example the unit test should be pretty simple to implement.
It should be something like that:
describe("path", () => {
let component: Component;
let fixture: ComponentFixture<Component>
let service: Service;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [Component],
providers: [Service]
});
fixture = TestBet.CreateComponent(Component)
service = TestBed.get(Service)
});
afterEach(() => {
fixture.destroy();
});
it("Component_Method_WhatDoYouExpect", () => {
let testCompanies = [{c1}....];
let spy = spyOn(service, "getCompanies").and.returnValue(testCompanies);
component.ngOnInit();
expect(spy).toHaveBeenCalled();
expect(component.companies).toEqual(testCompanies);
});
});
You have to create a test file for the component and one for the service.
In service test you should do almost the same like above, but there you have to initialize the company list, to call the method and to verify if the result is right.
service.companyList = [c1, c2...]
let res = service.GetCompanies();
expect(res).toEqual(service.companyList);
Here you can find more information about TestBed and Unit tests.