Skip to content

Commit

Permalink
Jest tests
Browse files Browse the repository at this point in the history
  • Loading branch information
suissa committed Jan 20, 2024
1 parent 2324933 commit 2333214
Show file tree
Hide file tree
Showing 10 changed files with 1,207 additions and 1,142 deletions.
2,010 changes: 901 additions & 1,109 deletions package-lock.json

Large diffs are not rendered by default.

19 changes: 19 additions & 0 deletions src/connection/service/connection.model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
export class Connection {
_id?: string;
name: string;
phone: string;
instanceName: string;
instanceStatus: boolean;
messages: [];
isActive?: boolean;
createdAt?: Date;
updatedAt?: Date;

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

public toObject() {
return this;
}
}
98 changes: 98 additions & 0 deletions src/connection/service/connection.service.specspec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
import { Test, TestingModule } from "@nestjs/testing";
import { ConnectionService } from "./connection.service";
import { getModelToken } from "@nestjs/mongoose";
import { Model } from "mongoose";
import { Connection } from "./connection.model";
import { Query } from "mongoose";
import { CreateConnectionDto } from "../dto/create-connection.dto";
import { EvolutionService } from "../../evolution/service/evolution.service";


describe("ConnectionService", () => {
let service: ConnectionService;
let connectionModel: Model<Connection>;

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

service = module.get<ConnectionService>(ConnectionService);
connectionModel = module.get<Model<Connection>>(getModelToken(Connection.name));
});

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

describe("create", () => {
it("should create a new connection", async () => {
const request: CreateConnectionDto = {
name: "Test Connection",
phone: "123456789",
instanceName: "test-instance",
instanceStatus: true,
};

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

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

const result = await service.create(request);

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


// describe("findAll", () => {
// it("should find all companies", async () => {
// const mockConnectionData = [
// new Connection({
// name: "Test Connection",
// phone: "123456789",
// instanceName: "test-instance",
// instanceStatus: true,
// toObject: function () { return this; },
// }),
// ];

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

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

// const result = await service.findAll();

// expect(mockPopulateResult).toHaveBeenCalled();
// expect(mockSortResult).toHaveBeenCalled();
// expect(mockExecResult).toHaveBeenCalled();
// expect(result).toEqual(mockConnectionData.map((item) => { return item.toObject(); }));
// });
// });
});
10 changes: 5 additions & 5 deletions src/connection/service/connection.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ import { BadRequestException, NotFoundException, Injectable } from "@nestjs/comm
import { InjectModel } from "@nestjs/mongoose";
import { Connection } from "../schema/connection.schema";
import mongoose, { Model } from "mongoose";
import { UpdateConnectionDto } from "src/connection/dto/update-connection.dto";
import { CreateConnectionDto } from "src/connection/dto/create-connection.dto";
import { EvolutionService } from "src/evolution/service/evolution.service"
import { UpdateConnectionDto } from "../../connection/dto/update-connection.dto";
import { CreateConnectionDto } from "../../connection/dto/create-connection.dto";
import { EvolutionService } from "../../evolution/service/evolution.service"
import axios from "axios";
// const SERVER_EVOLUTION = process.env.SERVER_EVOLUTION || "http://localhost:6666";
const SERVER_EVOLUTION = "http://137.184.81.207:6666";
const SERVER_EVOLUTION = process.env.SERVER_EVOLUTION || "http://localhost:6666";
// const SERVER_EVOLUTION = "http://137.184.81.207:6666";
@Injectable()
export class ConnectionService {
constructor(
Expand Down
24 changes: 12 additions & 12 deletions src/contact/dto/create-contact.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,21 +65,21 @@ export class CreateContactDto {
@IsString()
profilePictureUrl: string = "/images/avatar-01.png";

@IsString()
@IsOptional()
ticketStatus: string = "inativo";
// @IsString()
// @IsOptional()
// ticketStatus: string = "inativo";

@IsString()
@IsOptional()
ticketCreatedAt: string;
// @IsString()
// @IsOptional()
// ticketCreatedAt: string;

@IsString()
@IsOptional()
ticketClosedAt: string;
// @IsString()
// @IsOptional()
// ticketClosedAt: string;

@IsString()
@IsOptional()
transferedTo: string;
// @IsString()
// @IsOptional()
// transferedTo: string;

@IsArray()
@IsString({ each: true })
Expand Down
20 changes: 10 additions & 10 deletions src/contact/schema/contact.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,20 +54,20 @@ export class Contact {
@Prop({ default: "/images/avatar-01.png"})
profilePictureUrl: string;

@Prop({ default: "inativo"})
ticketStatus: string;
// @Prop({ default: "inativo"})
// ticketStatus: string;

@Prop()
ticketCreatedAt: string;
// @Prop()
// ticketCreatedAt: string;

@Prop()
ticketClosedAt: string;
// @Prop()
// ticketClosedAt: string;

@Prop()
transferedTo: string;
// @Prop()
// transferedTo: string;

@Prop()
connectionPhone: string;
// @Prop()
// connectionPhone: string;

@Prop()
groupId: string;
Expand Down
25 changes: 25 additions & 0 deletions src/contact/service/contact.model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
export class Contact {
_id?: string;
name: string;
phone: string;
email: string;
status: string;
city: string;
state: string;
country: string;
profilePictureUrl: string;
badges: [];
messages: [];
// groupId: string;
isActive?: boolean;
createdAt?: Date;
updatedAt?: Date;

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

public toObject() {
return this;
}
}
131 changes: 131 additions & 0 deletions src/contact/service/contact.service.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
import { Test, TestingModule, mockResolvedValue } from "@nestjs/testing";
import { ContactService } from "./contact.service";
import { ConnectionService } from "../../connection/service/connection.service";
import { EvolutionService } from "../../evolution/service/evolution.service";
import { getModelToken } from "@nestjs/mongoose";
import { Model } from "mongoose";
import { Contact } from "./contact.model";
import { Query } from "mongoose";
import { CreateContactDto } from "../dto/create-contact.dto";


describe("ContactService", () => {
let service: ContactService;
let contactModel: Model<Contact>;

const mockConnectionService = {
getConnectionByInstanceName: jest.fn().mockResolvedValue({}),
};

const mockEvolutionService = {
sendSimpleMessage: jest.fn().mockResolvedValue({

}),
};

beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
ContactService,
{
provide: ConnectionService,
useValue: mockConnectionService, // Forneça um mock para ConnectionService
},
{
provide: EvolutionService,
useValue: mockEvolutionService, // Forneça um mock para EvolutionService
},
{
provide: getModelToken(Contact.name),
useValue: {
create: jest.fn(),
find: jest.fn(),
findOne: jest.fn(),
findByIdAndUpdate: jest.fn(),
updateMany: jest.fn(),
findByIdAndDelete: jest.fn(),
},
},
],
}).compile();

service = module.get<ContactService>(ContactService);
contactModel = module.get<Model<Contact>>(getModelToken(Contact.name));
});

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

describe("create", () => {
it("should create a new contact", async () => {
const request: CreateContactDto = {
name: "Test Contact",
phone: "123456789",
email: "[email protected]",
status: "ativo",
city: "cidade",
state: "AC",
country: "Brasil",
profilePictureUrl: "",
badges: ["teste"],
messages: [],
};

const expectedResult = {
...request,
_id: "6586033c9f031a4394c1852f",
createdAt: new Date(),
updatedAt: new Date(),
badges: [], // Explicitly define the type of badges as an empty array
};

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

const result = await service.create(request);

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


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

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

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

// const result = await service.findAll();

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

});
4 changes: 2 additions & 2 deletions src/contact/service/contact.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import { Contact } from "../schema/contact.schema";
import mongoose, { Model } from "mongoose";
import { UpdateContactDto } from "../dto/update-contact.dto";
import { CreateContactDtoPartial } from "../dto/create-contact.dto";
import { ConnectionService } from "src/connection/service/connection.service";
import { EvolutionService } from "src/evolution/service/evolution.service"
import { ConnectionService } from "../../connection/service/connection.service";
import { EvolutionService } from "../../evolution/service/evolution.service"


interface ImportContactsRequest {
Expand Down
8 changes: 4 additions & 4 deletions src/evolution/service/evolution.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ import { InjectModel } from "@nestjs/mongoose";
// import mongoose, { Model } from "mongoose";
import { ConfigService } from "@nestjs/config";
import { Evolution } from "../schema/evolution.schema";
import { MessageGateway } from "src/gateways/message.gateway";
import { CreateEvolutionDto } from "src/evolution/dto/create-instance.dto";
import { CreateMessageDto } from "src/evolution/dto/create-message.dto";
import { GetInstanceDto } from "src/evolution/dto/get-instance.dto";
import { MessageGateway } from "../../gateways/message.gateway";
import { CreateEvolutionDto } from "../../evolution/dto/create-instance.dto";
import { CreateMessageDto } from "../../evolution/dto/create-message.dto";
import { GetInstanceDto } from "../../evolution/dto/get-instance.dto";
import * as amqp from "amqplib";
import axios from "axios";

Expand Down

0 comments on commit 2333214

Please sign in to comment.