Skip to content

Commit

Permalink
Merge pull request #5 from suissa/develop
Browse files Browse the repository at this point in the history
Auth and Company tests and Github Actions
  • Loading branch information
suissa authored Jan 17, 2024
2 parents 290b2ec + 6ed747d commit 69c0d43
Show file tree
Hide file tree
Showing 9 changed files with 199 additions and 13 deletions.
32 changes: 32 additions & 0 deletions .github/workflows/nest.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
name: Node.js CI

on:
push:
branches: [ main ]
pull_request:
branches: [ main ]

jobs:
build:
runs-on: ubuntu-latest

strategy:
matrix:
node-version: [18.x, 20.x] # Defina as versões do Node.js que você quer testar

steps:
- uses: actions/checkout@v2

- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}

- name: Install dependencies
run: npm install

- name: Build
run: npm run build

- name: Run tests
run: npm test
6 changes: 3 additions & 3 deletions package-lock.json

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

6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@
"@nestjs/testing": "^10.0.0",
"@types/bcrypt": "^5.0.2",
"@types/express": "^4.17.17",
"@types/jest": "^29.5.2",
"@types/jest": "^29.5.11",
"@types/node": "^20.3.1",
"@types/passport-local": "^1.0.38",
"@types/supertest": "^2.0.12",
Expand All @@ -70,11 +70,11 @@
"eslint": "^8.42.0",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-prettier": "^5.0.0",
"jest": "^29.5.0",
"jest": "^29.7.0",
"prettier": "^3.0.0",
"source-map-support": "^0.5.21",
"supertest": "^6.3.3",
"ts-jest": "^29.1.0",
"ts-jest": "^29.1.1",
"ts-loader": "^9.4.3",
"ts-node": "^10.9.1",
"tsconfig-paths": "^4.2.0",
Expand Down
21 changes: 20 additions & 1 deletion src/auth/auth.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,29 @@
import { Test, TestingModule } from '@nestjs/testing';
import { AuthService } from './auth.service';
import { User } from '../user/schema/user.schema'; // Ajuste o caminho conforme necessário
import { Model } from 'mongoose';
import { getModelToken } from '@nestjs/mongoose';
import { find } from 'rxjs';

const mockUserModel = {
findOne: jest.fn(),
find: jest.fn(),
updateOne: jest.fn(),
updateMany: jest.fn(),
};

describe('AuthService', () => {
let service: AuthService;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [AuthService],
providers: [
AuthService,
{
provide: getModelToken(User.name),
useValue: mockUserModel,
},
],
}).compile();

service = module.get<AuthService>(AuthService);
Expand All @@ -15,4 +32,6 @@ describe('AuthService', () => {
it('should be defined', () => {
expect(service).toBeDefined();
});


});
6 changes: 3 additions & 3 deletions src/auth/auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { Injectable } from "@nestjs/common";
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { InjectModel } from "@nestjs/mongoose";
import { Model } from "mongoose";
import * as bcrypt from "bcrypt";
import * as jwt from "jsonwebtoken";
import mongoose from "mongoose";
import { User } from 'src/user/schema/user.schema'; // Ajuste o caminho conforme necessário
import { User } from "../user/schema/user.schema"; // Ajuste o caminho conforme necessário

const SECRET = "ManoVeioPeriferico#666"
@Injectable()
Expand Down
2 changes: 1 addition & 1 deletion src/company/controller/company.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {
import { CompanyService } from "../service/company.service";
import { CreateCompanyDto } from "../dto/create-company.dto";
// import { UpdateCompanytDto } from "../dto/update-company.dto";
import { JwtAuthGuard } from 'src/auth/guards/jwt-auth.guard';
import { JwtAuthGuard } from '../../auth/guards/jwt-auth.guard';

@UseGuards(JwtAuthGuard)
@Controller("companies")
Expand Down
8 changes: 6 additions & 2 deletions src/company/dto/create-company.dto.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { IsNotEmpty, IsString, IsOptional, IsBoolean } from 'class-validator';
import { IsNotEmpty, IsString, IsOptional, IsBoolean, IsObject } from 'class-validator';

export class CreateCompanyDto {
@IsNotEmpty()
Expand All @@ -17,9 +17,13 @@ export class CreateCompanyDto {
@IsString()
status: string;

@IsObject()
@IsOptional()
planId: {}; // Representando um ObjectId como string

@IsString()
@IsOptional()
planId: string; // Representando um ObjectId como string
planName: string; // Representando um ObjectId como string

@IsBoolean()
@IsOptional()
Expand Down
22 changes: 22 additions & 0 deletions src/company/service/company.model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
export class Company {
_id?: string;
name: string;
phone: string;
password: string;
status: string;
planId: {};
planName?: string;
campaignsEnabled?: boolean;
dueDate?: string;
recurrence?: boolean;
createdAt?: Date;
updatedAt?: Date;

constructor(partial: Partial<Company>) {
Object.assign(this, partial);
}

public toObject() {
return this;
}
}
109 changes: 109 additions & 0 deletions src/company/service/company.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import { Test, TestingModule } from "@nestjs/testing";
import { CompanyService } from "./company.service";
import { getModelToken } from "@nestjs/mongoose";
import { Model } from "mongoose";
import { Company } from "./company.model";
import { Query } from "mongoose";
import { CreateCompanyDto } from "../dto/create-company.dto";

describe("CompanyService", () => {
let service: CompanyService;
let companyModel: Model<Company>;

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
CompanyService,
{
provide: getModelToken(Company.name),
useValue: {
create: jest.fn(),
find: jest.fn(),
findOne: jest.fn(),
findByIdAndUpdate: jest.fn(),
updateMany: jest.fn(),
findByIdAndDelete: jest.fn(),
},
},
],
}).compile();

service = module.get<CompanyService>(CompanyService);
companyModel = module.get<Model<Company>>(getModelToken(Company.name));
});

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

describe("create", () => {
it("should create a new company", async () => {
const request: CreateCompanyDto = {
name: "example",
planId: "example",
planName: "example",
isActive: true,
status: "example",
dueDate: new Date().toString(),
recurrence: true,
phone: "example",
password: "example",
campaignsEnabled: true, // Updated to string value
};

const expectedResult = new Company({
...request,
_id: "6586033c9f031a4394c1852f",
createdAt: new Date(),
updatedAt: new Date(),
});

jest.spyOn(companyModel, "create").mockResolvedValue(expectedResult as any);

const result = await service.create(request);

expect(companyModel.create).toHaveBeenCalledWith(request);
expect(result).toEqual(expectedResult);
});
});


describe("findAll", () => {
it("should find all companies", async () => {
const mockCompanyData = [
new Company({
name: "Test Company",
phone: "123456789",
planName: "Test Plan",
planId: "Test Plan",
toObject: function () { return this; },
}),
];

const mockExecResult = jest.fn().mockResolvedValue(mockCompanyData);
const mockSortResult = jest.fn().mockReturnThis();
const mockPopulateResult = jest.fn().mockReturnThis();

jest.spyOn(companyModel, "find").mockImplementation(() => ({
populate: mockPopulateResult,
sort: mockSortResult,
exec: mockExecResult,
}) as unknown as Query<unknown[], unknown, {}, Company, "find">);

const result = await service.findAll();

expect(mockPopulateResult).toHaveBeenCalled();
expect(mockSortResult).toHaveBeenCalled();
expect(mockExecResult).toHaveBeenCalled();
expect(result).toEqual(mockCompanyData.map(company => {
const companyObj = company.toObject();
const planName = (company.planId as any).name; // Casting para Plan, pois sabemos que foi populado
return {
...companyObj,
planName // Adiciona a propriedade planName com o valor do nome do plano
};
}));
});
});

});

0 comments on commit 69c0d43

Please sign in to comment.