Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test(sample-07): added unit tests #8044

Merged
merged 20 commits into from
Oct 21, 2021
Merged
Show file tree
Hide file tree
Changes from 19 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
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
10 changes: 10 additions & 0 deletions sample/07-sequelize/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

20 changes: 19 additions & 1 deletion sample/07-sequelize/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,12 @@
"typescript": "4.3.5"
},
"devDependencies": {
"@types/sequelize": "4.28.10",
"@nestjs/cli": "8.1.4",
"@types/sequelize": "4.28.10",
"@nestjs/schematics": "8.0.4",
"@nestjs/testing": "8.1.1",
"@types/express": "4.17.13",
"@types/jest": "^27.0.1",
"@types/node": "14.17.27",
"@types/supertest": "2.0.11",
"@types/ws": "7.4.7",
Expand All @@ -53,5 +54,22 @@
"eslint-config-prettier": "8.3.0",
"eslint-plugin-import": "2.25.2",
"typescript": "4.3.5"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Column, Model, Table } from 'sequelize-typescript';

@Table
export class User extends Model<User> {
export class User extends Model {
@Column
firstName: string;

Expand Down
94 changes: 94 additions & 0 deletions sample/07-sequelize/src/users/users.controller.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import { Test, TestingModule } from '@nestjs/testing';
import { CreateUserDto } from './dto/create-user.dto';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';

const createUserDto: CreateUserDto = {
firstName: 'firstName #1',
lastName: 'lastName #1',
};

describe('UsersController', () => {
let usersController: UsersController;
let usersService: UsersService;

beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [UsersController],
providers: [
{
provide: UsersService,
useValue: {
create: jest
.fn()
.mockImplementation((user: CreateUserDto) =>
Promise.resolve({ id: '1', ...user }),
),
findAll: jest.fn().mockResolvedValue([
{
firstName: 'firstName #1',
lastName: 'lastName #1',
},
{
firstName: 'firstName #2',
lastName: 'lastName #2',
},
]),
findOne: jest.fn().mockImplementation((id: string) =>
Promise.resolve({
firstName: 'firstName #1',
lastName: 'lastName #1',
id,
}),
),
remove: jest.fn(),
},
},
],
}).compile();

usersController = app.get<UsersController>(UsersController);
usersService = app.get<UsersService>(UsersService);
});

it('should be defined', () => {
expect(usersController).toBeDefined();
});

describe('create()', () => {
it('should create an user', () => {
Tony133 marked this conversation as resolved.
Show resolved Hide resolved
expect(usersController.create(createUserDto)).resolves.toEqual({
id: '1',
...createUserDto,
});
expect(usersService.create).toHaveBeenCalled();
expect(usersService.create).toHaveBeenCalledWith(createUserDto);
});
});

describe('findAll()', () => {
it('should find all users ', () => {
usersController.findAll();
expect(usersService.findAll).toHaveBeenCalled();
});
});

describe('findOne()', () => {
it('should find a user', () => {
usersController.findOne('1');
expect(usersService.findOne).toHaveBeenCalled();
expect(usersController.findOne('1')).resolves.toEqual({
firstName: 'firstName #1',
lastName: 'lastName #1',
id: '1',
});
});
});

describe('remove()', () => {
it('should remove the user', () => {
usersController.remove('2');
expect(usersService.remove).toHaveBeenCalled();
});
});
});
2 changes: 1 addition & 1 deletion sample/07-sequelize/src/users/users.controller.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Body, Controller, Delete, Get, Param, Post } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { User } from './user.model';
import { User } from './models/user.model';
import { UsersService } from './users.service';

@Controller('users')
Expand Down
2 changes: 1 addition & 1 deletion sample/07-sequelize/src/users/users.module.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Module } from '@nestjs/common';
import { SequelizeModule } from '@nestjs/sequelize';
import { User } from './user.model';
import { User } from './models/user.model';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';

Expand Down
91 changes: 91 additions & 0 deletions sample/07-sequelize/src/users/users.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import { Test, TestingModule } from '@nestjs/testing';
import { User } from './models/user.model';
import { UsersService } from './users.service';
import { getModelToken } from '@nestjs/sequelize';

const usersArray = [
{
firstName: 'firstName #1',
lastName: 'lastName #1',
},
{
firstName: 'firstName #2',
lastName: 'lastName #2',
},
];

const oneUser = {
firstName: 'firstName #1',
lastName: 'lastName #1',
};

describe('UserService', () => {
let service: UsersService;
let model: typeof User;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
UsersService,
{
provide: getModelToken(User),
useValue: {
findAll: jest.fn(() => usersArray),
findOne: jest.fn(),
create: jest.fn(() => oneUser),
remove: jest.fn(),
destroy: jest.fn(() => oneUser),
},
},
],
}).compile();

service = module.get<UsersService>(UsersService);
model = module.get<typeof User>(getModelToken(User));
});

it('should be defined', () => {
expect(service).toBeDefined();
});

describe('create()', () => {
it('should successfully insert a user', () => {
const oneUser = {
firstName: 'firstName #1',
lastName: 'lastName #1',
};
expect(
service.create({
firstName: 'firstName #1',
lastName: 'lastName #1',
}),
).toEqual(oneUser);
});
});

describe('findAll()', () => {
it('should return an array of users', async () => {
const users = await service.findAll();
expect(users).toEqual(usersArray);
});
});

describe('findOne()', () => {
it('should get a single user', () => {
const findSpy = jest.spyOn(model, 'findOne');
expect(service.findOne('1'));
expect(findSpy).toBeCalledWith({ where: { id: '1' } });
});
});

describe('remove()', () => {
it('should remove a user', async () => {
const findSpy = jest.spyOn(model, 'findOne').mockReturnValue({
destroy: jest.fn(),
} as any);
const retVal = await service.remove('2');
expect(findSpy).toBeCalledWith({ where: { id: '2' } });
expect(retVal).toBeUndefined();
});
});
});
8 changes: 2 additions & 6 deletions sample/07-sequelize/src/users/users.service.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/sequelize';
import { CreateUserDto } from './dto/create-user.dto';
import { User } from './user.model';
import { User } from './models/user.model';

@Injectable()
export class UsersService {
Expand All @@ -11,11 +11,7 @@ export class UsersService {
) {}

create(createUserDto: CreateUserDto): Promise<User> {
const user = new User();
user.firstName = createUserDto.firstName;
user.lastName = createUserDto.lastName;

return user.save();
return this.userModel.create(createUserDto);
}

async findAll(): Promise<User[]> {
Expand Down