property signin, sign up does not exist on type AuthService - nestjs

auth.controller file
`import { Test, TestingModule } from '#nestjs/testing';
import { AuthController } from './auth.controller';
describe('AuthController', () => {
let controller: AuthController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
controllers: [AuthController],
}).compile();
controller = module.get<AuthController>(AuthController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
});`
auth.service file
`import { Injectable } from '#nestjs/common';
#Injectable({})
export class AuthService {
signin()
{
return { msg: 'i am signin' };
}
signup()
{
return { msg: 'i am signup' };
}
}`
i am beginner level and getting this type of error even if remove all the code to simple return message my vcode gives same error what can be the issue

I'm surprised you're not getting a Dependency Injection error related to a missing AuthService dependency. You need to provide a custom provider for the AuthService to inject into the AuthController for the purpose of testing.
This repository has a lot of testing examples to take a look at

Related

NestJS unitesting Middleware

I'm trying to unit test a middleware to avoid sending a request but I'm actually not able to retreive the middleware with .get
import { NestApplicationContext } from '#nestjs/core';
import { BodyParserMiddleware } from '../../../src/config/body-parser/body-parser.middleware';
import { FeaturesModule } from '../../../src/features/features.module';
describe('CatsController', () => {
let app: NestApplicationContext;
beforeAll(() => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
}).compile();
app = moduleFixture.createNestApplication();
});
describe('findAll', () => {
it('should return an array of cats', async () => {
console.log(app.get(BodyParserMiddleware));
});
});
});
my app module looks like this
import { Module } from '#nestjs/common';
import { FeaturesModule } from './features/features.module';
#Module({
imports: [FeaturesModule],
})
export class AppModule {}
and the last one feature module
import { MiddlewareConsumer, Module, NestModule } from '#nestjs/common';
import { BodyParserMiddleware } from '../config/body-parser/body-parser.middleware';
#Module({
imports: [
AuthModule,
],
})
export class FeaturesModule implements NestModule {
configure(consumer: MiddlewareConsumer): void {
consumer.apply(BodyParserMiddleware).forRoutes('api/v*/*/get-many');
}
}
Nest could not find BodyParserMiddleware element (this provider does not exist in the current context)
this is the error that im having
anyone knows how to retreive the middleware from the app container?
Also when I try to get the Features module to see if there is any clue there where I can go I receive
FeaturesModule {}

JEST How to mock getManager().query from NestJS

Hi I'm trying to test my service but got stuck
import { HttpException, Injectable } from '#nestjs/common';
import { InjectRepository } from '#nestjs/typeorm';
import { getManager, Repository } from 'typeorm';
import { PointsEntity } from './entities/point_store.entity';
#Injectable()
export class PointStoreService {
constructor(
#InjectRepository(PointsEntity)
private readonly pointsRepository: Repository<PointsEntity>,
) {}
async searchPoints(startDate: Date, endDate: Date, userId: string) {
try {
return await getManager().query(`
SELECT * FROM points WHERE expire_at
BETWEEN '${startDate.toISOString()}' AND '${endDate.toISOString()}'
AND "userId"='${userId}'
`);
} catch (err) {
throw new HttpException(err.message, err.state ? err.state : 500);
}
}
}
This is my Service code. As you know there is only one method.
import { Test, TestingModule } from '#nestjs/testing';
import { getRepositoryToken } from '#nestjs/typeorm';
import * as typeorm from 'typeorm';
import { PointsEntity } from './entities/point_store.entity';
import { PointStoreService } from './point_store.service';
const mockPointsRepository = {
save: jest.fn(),
};
describe('PointStoreService', () => {
let service: PointStoreService;
let repository: typeorm.Repository<PointsEntity>;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
PointStoreService,
{
provide: getRepositoryToken(PointsEntity),
useValue: mockPointsRepository,
},
],
}).compile();
jest.resetModules(); // Most important - it clears the cache
service = module.get<PointStoreService>(PointStoreService);
repository = module.get(getRepositoryToken(PointsEntity));
});
it('should be defined', () => {
expect(service).toBeDefined();
});
describe('searchPoints', () => {
it('should searchPoints', async () => {
// can not mock getManager!!!
jest.spyOn(getManager, 'query');
});
});
});
Now I code this test case. 'should be defined' works fine. But after I try to test 'should searchPoints', I have no idea to mock it.
Is there a way to mock getManager().query()?
gitHub repository

jest - how to test a function within a method

I have been trying for a long time and nothing works, how could I test the "compare" function inside the "methodName" method?
teste.spec.ts
import { Test, TestingModule } from '#nestjs/testing';
import { TesteService } from './teste.service';
describe('TesteService', () => {
let service: TesteService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [TesteService],
}).compile();
service = module.get<TesteService>(TesteService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
it('methodName need return a string', () => {
expect(service.methodName()).toEqual(typeof String)
})
});
teste.ts
import { Injectable } from '#nestjs/common';
import { compare } from 'bcrypt'
#Injectable()
export class TesteService {
methodName() {
const password = '123456789'
const checkPassword = compare('123456789', password)
return checkPassword ? 'correct' : 'wrong'
}
}
if i do it this way would it be okay?
it('compare password', () => {
const checkPassword = compare('123456789', '123456789')
expect(checkPassword).toBeTruthy()
})
As a principle in unit testing, we assume that external packages have been tested and are working. What you can do with your test, though, is to spy on the compare function and check weather your method is calling it and what it's calling with.
import * as bcrypt from 'bcrypt';
it('should call compare', () => {
const spyCompare = jest.spyOn(bcrypt, 'compare');
service.methodName();
expect(spyCompare).toHaveBeenCalled();
expect(spyCompare).toHaveBeenCalledWith('123456789');
})

Testing Passport in NestJS

I'm trying to do a e2e testing to a route that has an AuthGuard from nestjs passport module and I don't really know how to approach it. When I run the tests it says:
[ExceptionHandler] Unknown authentication strategy "bearer"
I haven't mock it yet so I suppose it's because of that but I don't know how to do it.
This is what I have so far:
player.e2e-spec.ts
import { Test } from '#nestjs/testing';
import { INestApplication } from '#nestjs/common';
import * as request from 'supertest';
import { PlayerModule } from '../src/modules/player.module';
import { PlayerService } from '../src/services/player.service';
import { Repository } from 'typeorm';
describe('/player', () => {
let app: INestApplication;
const playerService = { updatePasswordById: (id, password) => undefined };
beforeAll(async () => {
const module = await Test.createTestingModule({
imports: [PlayerModule],
})
.overrideProvider(PlayerService)
.useValue(playerService)
.overrideProvider('PlayerRepository')
.useClass(Repository)
.compile();
app = module.createNestApplication();
await app.init();
});
it('PATCH /password', () => {
return request(app.getHttpServer())
.patch('/player/password')
.expect(200);
});
});
player.module.ts
import { Module } from '#nestjs/common';
import { PlayerService } from 'services/player.service';
import { PlayerController } from 'controllers/player.controller';
import { TypeOrmModule } from '#nestjs/typeorm';
import { Player } from 'entities/player.entity';
import { PassportModule } from '#nestjs/passport';
#Module({
imports: [
TypeOrmModule.forFeature([Player]),
PassportModule.register({ defaultStrategy: 'bearer' }),
],
providers: [PlayerService],
controllers: [PlayerController],
exports: [PlayerService],
})
export class PlayerModule {}
Below is a e2e test for an auth API based using TypeORM and the passportjs module for NestJs. the auth/authorize API checks to see if the user is logged in. The auth/login API validates a username/password combination and returns a JSON Web Token (JWT) if the lookup is successful.
import { HttpStatus, INestApplication } from '#nestjs/common';
import { Test } from '#nestjs/testing';
import { TypeOrmModule } from '#nestjs/typeorm';
import * as request from 'supertest';
import { UserAuthInfo } from '../src/user/user.auth.info';
import { UserModule } from '../src/user/user.module';
import { AuthModule } from './../src/auth/auth.module';
import { JWT } from './../src/auth/jwt.type';
import { User } from '../src/entity/user';
describe('AuthController (e2e)', () => {
let app: INestApplication;
let authToken: JWT;
beforeAll(async () => {
const moduleFixture = await Test.createTestingModule({
imports: [TypeOrmModule.forRoot(), AuthModule],
}).compile();
app = moduleFixture.createNestApplication();
await app.init();
});
it('should detect that we are not logged in', () => {
return request(app.getHttpServer())
.get('/auth/authorized')
.expect(HttpStatus.UNAUTHORIZED);
});
it('disallow invalid credentials', async () => {
const authInfo: UserAuthInfo = {username: 'auser', password: 'badpass'};
const response = await request(app.getHttpServer())
.post('/auth/login')
.send(authInfo);
expect(response.status).toBe(HttpStatus.UNAUTHORIZED);
});
it('return an authorization token for valid credentials', async () => {
const authInfo: UserAuthInfo = {username: 'auser', password: 'goodpass'};
const response = await request(app.getHttpServer())
.post('/auth/login')
.send(authInfo);
expect(response.status).toBe(HttpStatus.OK);
expect(response.body.user.username).toBe('auser');
expect(response.body.user.firstName).toBe('Adam');
expect(response.body.user.lastName).toBe('User');
authToken = response.body.token;
});
it('should show that we are logged in', () => {
return request(app.getHttpServer())
.get('/auth/authorized')
.set('Authorization', `Bearer ${authToken}`)
.expect(HttpStatus.OK);
});
});
Note since this is an end-to-end test, it doesn't use mocking (at least my end-to-end tests don't :)). Hope this is helpful.
You can just generate a valid token and send it inside header for authentication using passport (jwt,...):
beforeAll(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
imports: [AppModule],
})
.compile();
productService = moduleFixture.get<ProductService>(ProductService);
userService = moduleFixture.get<UsersService>(UsersService);
authService = moduleFixture.get<AuthenticationService>(
AuthenticationService,
);
app = moduleFixture.createNestApplication();
await app.init();
});
afterAll(async () => {
await app.close();
});
beforeEach(async () => {
const signupResult = await authService.signup({
email: 'test#test.com',
name: 'test user',
password: 'testpassword',
});
accessToken = signupResult.token.access_token; // this line find a valid access token and you can pass this to your tests
});
Pass access_token to requests:
it('should return 201 and return product', async () => {
return request(app.getHttpServer())
.post('/products')
.set('Authorization', `Bearer ${accessToken}`) // this is for Authentication
.send({})
.expect(201)
.expect(({ body }) => {
expect(body.id).toBeDefined();
});
});

supertest e2e with nestjs: request is not a function

I try to introduce e2e tests for my simple NestJS backend services. I am providing a custom userService and a custom UserRepository mocked with sinon.
This is my user.e2e-spec.ts file:
import * as request from 'supertest';
import * as sinon from 'sinon';
import { Test } from '#nestjs/testing';
import { INestApplication } from '#nestjs/common';
import { UserService } from '../../src/user/user.service';
import { getRepositoryToken } from '#nestjs/typeorm';
import { User } from '../../src/user/user.entity';
import { TestUtil } from '../../src/utils/TestUtil';
import { createFakeUser } from '../../src/user/test/userTestUtil';
let sandbox: sinon.SinonSandbox;
let testUtil;
describe('User', () => {
let app: INestApplication;
const fakeUser = createFakeUser();
const userService = { findOne: () => fakeUser };
beforeAll(async () => {
sandbox = sinon.createSandbox();
testUtil = new TestUtil(sandbox);
const module = await Test.createTestingModule({
providers: [
{
provide: UserService,
useValue: userService,
},
{
provide: getRepositoryToken(User),
useValue: testUtil.getMockRepository().object,
},
],
}).compile();
app = module.createNestApplication();
await app.init();
});
it(`/GET user`, () => {
return request(app.getHttpServer())
.get('/user/:id')
.expect(200)
.expect({
data: userService.findOne(),
});
});
afterAll(async () => {
await app.close();
});
});
and this is my user.controller.ts:
import { ApiBearerAuth, ApiUseTags } from '#nestjs/swagger';
import { Controller, Get, Param } from '#nestjs/common';
import { UserService } from './user.service';
import { User } from './user.entity';
#ApiUseTags('Users')
#ApiBearerAuth()
#Controller('user')
export class UserController {
constructor(private readonly userService: UserService) {}
#Get('/:id')
findOne(#Param('id') id: number): Promise<User> {
return this.userService.find(id);
}
}
I wrote a bunch of Unit tests with the same pattern and it works. Have no clue what is wrong with this e2e supertest.
Thanks for your help!
UPDATE:
This is the error message I get:
TypeError: request is not a function
at Object.it (/Users/florian/Development/Houzy/nestjs-backend/e2e/user/user.e2e-spec.ts:40:16)
at Object.asyncFn (/Users/florian/Development/Houzy/nestjs-backend/node_modules/jest-jasmine2/build/jasmine_async.js:124:345)
at resolve (/Users/florian/Development/Houzy/nestjs-backend/node_modules/jest-jasmine2/build/queue_runner.js:46:12)
at new Promise (<anonymous>)
at mapper (/Users/florian/Development/Houzy/nestjs-backend/node_modules/jest-jasmine2/build/queue_runner.js:34:499)
at promise.then (/Users/florian/Development/Houzy/nestjs-backend/node_modules/jest-jasmine2/build/queue_runner.js:74:39)
at <anonymous>
Change import of request to:
import request from 'supertest';
In your test, replace :id with number:
it(`/GET user`, () => {
return request(app.getHttpServer())
.get('/user/1') // pass here id, not a string
.expect(200)
.expect({
data: userService.findOne(),
});
});
And in controller:
#Get('/:id')
findOne(#Param('id') id: number): Promise<User> {
return this.userService.find(id);
}
This should work now.

Resources