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 8 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.

21 changes: 20 additions & 1 deletion sample/07-sequelize/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,13 @@
"typescript": "4.3.5"
},
"devDependencies": {
"@types/sequelize": "4.28.10",
"@nestjs/cli": "8.1.2",
"@types/sequelize": "4.28.10",
"@nestjs/schematics": "8.0.3",
"@nestjs/testing": "8.0.11",
"@types/express": "4.17.13",
"@types/jest": "^27.0.1",
"@types/sequelize": "4.28.10",
Tony133 marked this conversation as resolved.
Show resolved Hide resolved
"@types/node": "14.17.26",
"@types/supertest": "2.0.11",
"@types/ws": "7.4.7",
Expand All @@ -53,5 +55,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"
}
}
2 changes: 2 additions & 0 deletions sample/07-sequelize/src/app.module.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Module } from '@nestjs/common';
import { SequelizeModule } from '@nestjs/sequelize';
import { User } from './users/models/user.model';
Tony133 marked this conversation as resolved.
Show resolved Hide resolved
import { UsersModule } from './users/users.module';

@Module({
Expand All @@ -13,6 +14,7 @@ import { UsersModule } from './users/users.module';
database: 'test',
autoLoadModels: true,
synchronize: true,
models: [User],
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this needed? (and how can we avoid making this change)

Copy link
Contributor Author

@Tony133 Tony133 Oct 18, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I followed the directions in the documentation: https://docs.nestjs.com/techniques/database#models ,
by adding the models in SequelizeModule.forRoot({...})

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This shouldn't be required when autoLoadModels is set to true

Copy link
Contributor Author

@Tony133 Tony133 Oct 19, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wouldn't want to be wrong, but in sequelize version 5, registering the model in SequelizeModule.forRoot ({...}) was an alternative to extending the Model class, like this example export class Post extends Model<Post> {.... }.

Now from version 6, under the hood of sequelize something seems to have changed, so as you said autoLoadModels: true automatically loads the Modules if set to true, similar to TypeORM, now I tried to remove models:[] and it seems to work.

Maybe we should update the documents for this, what do you think?

Then I wanted to ask you but is the models:[] setting still useful to use? maybe you could remove it as a setting?

}),
UsersModule,
],
Expand Down
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
96 changes: 96 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,96 @@
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: [
UsersService,
Tony133 marked this conversation as resolved.
Show resolved Hide resolved
{
provide: UsersService,
useValue: {
create: jest
.fn()
.mockImplementation((user: CreateUserDto) =>
Promise.resolve({ id: 'a id', ...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
usersController.create(createUserDto);
expect(usersService.create).toHaveBeenCalled();
expect(usersService.create).toHaveBeenCalledWith(createUserDto);
expect(usersController.create(createUserDto)).resolves.toEqual({
id: 'a id',
Tony133 marked this conversation as resolved.
Show resolved Hide resolved
...createUserDto,
});
Tony133 marked this conversation as resolved.
Show resolved Hide resolved
});
});

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

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

describe('remove()', () => {
it('should remove the user', () => {
usersController.remove('anyid');
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
3 changes: 2 additions & 1 deletion sample/07-sequelize/src/users/users.module.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
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';

@Module({
imports: [SequelizeModule.forFeature([User])],
providers: [UsersService],
controllers: [UsersController],
exports: [SequelizeModule],
Tony133 marked this conversation as resolved.
Show resolved Hide resolved
})
export class UsersModule {}
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 userArray = [
Tony133 marked this conversation as resolved.
Show resolved Hide resolved
{
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(() => userArray),
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(userArray);
});
});

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

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('id');
expect(findSpy).toBeCalledWith({ where: { id: 'id' } });
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