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

Adição de testes de cobertura #12

Merged
merged 5 commits into from
Aug 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
25 changes: 0 additions & 25 deletions src/Controllers/bankAccountController.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
const createBankAccount = async (req, res) => {
try {
// Log dos dados recebidos para depuração
console.log("Dados recebidos:", req.body);

Check warning on line 8 in src/Controllers/bankAccountController.js

View workflow job for this annotation

GitHub Actions / lint

Unexpected console statement

// Acessando dados diretamente
const formData = req.body.formData || {}; // Fallback para objeto vazio se formData estiver ausente
Expand All @@ -26,11 +26,11 @@
// Criação de uma nova conta bancária
const bankAccount = new BankAccount(formData);
await bankAccount.save(); // Salvando a conta bancária no banco de dados
console.log("Conta bancária criada com sucesso:", bankAccount);

Check warning on line 29 in src/Controllers/bankAccountController.js

View workflow job for this annotation

GitHub Actions / lint

Unexpected console statement
res.status(201).send(bankAccount); // Enviando resposta de sucesso
} catch (error) {
// Log do erro para depuração
console.error("Erro ao criar conta bancária:", error.message);

Check warning on line 33 in src/Controllers/bankAccountController.js

View workflow job for this annotation

GitHub Actions / lint

Unexpected console statement
res.status(400).send({ error: error.message }); // Enviando erro caso ocorra
}
};
Expand All @@ -44,30 +44,6 @@
}
};

const getBankAccount = async (req, res) => {
try {
// Retorna apenas a conta bancária do nome fornecido
if (req.query.name) {
const bankAccount = await BankAccount.findOne({
name: req.query.name,
});

if (bankAccount) {
return res.status(200).json(bankAccount);
} else {
return res
.status(404)
.json({ message: "Conta não encontrada" });
}
} else {
return res.status(400).json({ message: "Nome não fornecido" });
}
} catch (error) {
console.error(error);
return res.status(500).json({ message: "Erro interno do servidor" });
}
};

const getBankAccountbyId = async (req, res) => {
try {
const bankAccount = await BankAccount.findById(req.params.id); // Buscando conta pelo ID
Expand All @@ -77,7 +53,7 @@
res.status(200).json(bankAccount); // Enviando conta bancária encontrada
} catch (error) {
// Log do erro para depuração
console.error("Erro ao buscar conta bancária:", error.message);

Check warning on line 56 in src/Controllers/bankAccountController.js

View workflow job for this annotation

GitHub Actions / lint

Unexpected console statement
res.status(500).send({ error: error.message }); // Enviando mensagem de erro
}
};
Expand All @@ -91,7 +67,7 @@
res.status(200).send({ message: "Conta deletada com sucesso" });
} catch (error) {
// Log do erro para depuração
console.error("Erro ao deletar conta bancária:", error.message);

Check warning on line 70 in src/Controllers/bankAccountController.js

View workflow job for this annotation

GitHub Actions / lint

Unexpected console statement
res.status(500).send({ error: error.message }); // Enviando mensagem de erro
}
};
Expand All @@ -104,7 +80,7 @@
}

// Log dos dados recebidos
console.log("Dados recebidos para atualização:", req.body);

Check warning on line 83 in src/Controllers/bankAccountController.js

View workflow job for this annotation

GitHub Actions / lint

Unexpected console statement

// Atualizar apenas os campos fornecidos
const bankAccount = await BankAccount.findByIdAndUpdate(id, req.body, {
Expand All @@ -117,14 +93,13 @@

res.status(200).send(bankAccount);
} catch (error) {
console.error("Erro ao atualizar conta bancária:", error.message);

Check warning on line 96 in src/Controllers/bankAccountController.js

View workflow job for this annotation

GitHub Actions / lint

Unexpected console statement
res.status(500).send({ error: error.message });
}
};

module.exports = {
createBankAccount,
getBankAccount,
deleteBankAccount,
getBankAccountbyId,
updateBankAccount,
Expand Down
2 changes: 1 addition & 1 deletion src/Controllers/supplierFormController.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const createSupplierForm = async (req, res) => {
message = util.validator(req.body.supplierData);

if (message) {
return res.status(404).send({ erro: message });
return res.status(400).send({ erro: message });
}

const supplier = new SupplierForm(req.body.supplierData);
Expand Down
87 changes: 81 additions & 6 deletions src/__tests__/bankAccountController.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
},
});

console.log("Create Response:", response); // Adicione um log para depuração

Check warning on line 41 in src/__tests__/bankAccountController.test.js

View workflow job for this annotation

GitHub Actions / lint

Unexpected console statement

expect(response.status).toBe(201);
expect(response.body).toHaveProperty("name", "Conta Teste");
Expand Down Expand Up @@ -67,19 +67,27 @@
},
});

console.log("Conflict Response:", response.body); // Adicione um log para depuração

Check warning on line 70 in src/__tests__/bankAccountController.test.js

View workflow job for this annotation

GitHub Actions / lint

Unexpected console statement

expect(response.status).toBe(409);
expect(response.body.error).toBe("Nome já cadastrado");
});

it("should fetch all bank accounts", async () => {
const response = await request(app).get("/finance/getBankAccount"); // Atualize o caminho da rota

console.log("Fetch All Response:", response.body); // Adicione um log para depuração
it("should not create a bank account with a blank name", async () => {
const response = await request(app)
.post("/finance/createBankAccount") // Atualize o caminho da rota
.send({
formData: {
name: "",
bank: "Banco Teste",
accountNumber: "12345678",
status: "Ativo",
accountType: "Conta Corrente",
},
});

expect(response.status).toBe(200);
expect(Array.isArray(response.body)).toBe(true);
expect(response.status).toBe(400);
expect(response.body.error).toBe("Nome não fornecido");
});

it("should fetch a bank account by ID", async () => {
Expand All @@ -105,6 +113,34 @@
expect(response.body.name).toBe("Conta Teste ID");
});

it("should not fetch a bank account without ID", async () => {
await request(app)
.post("/finance/createBankAccount") // Atualize o caminho da rota
.send({
formData: {
name: "Conta Teste ID",
bank: "Banco Teste ID",
accountNumber: "11111111",
status: "Ativo",
accountType: "Conta Corrente",
},
});

const response = await request(app).get(`/finance/bankAccount/${null}`); // Atualize o caminho da rota

console.log("Fetch By ID Response:", response.body); // Adicione um log para depuração

expect(response.status).toBe(500);
});
it("should fetch all bank accounts", async () => {
const response = await request(app).get("/finance/getBankAccount"); // Atualize o caminho da rota

console.log("Fetch All Response:", response.body); // Adicione um log para depuração

expect(response.status).toBe(200);
expect(response.body.length).toBe(2);
});

it("should update a bank account", async () => {
const newAccount = await request(app)
.post("/finance/createBankAccount") // Atualize o caminho da rota
Expand All @@ -128,6 +164,28 @@
expect(response.body.name).toBe("Conta Atualizada");
});

it("should not update a bank account without id", async () => {
await request(app)
.post("/finance/createBankAccount") // Atualize o caminho da rota
.send({
formData: {
name: "Conta a ser Atualizada",
bank: "Banco Teste Atualização",
accountNumber: "22222222",
status: "Ativo",
accountType: "Conta Corrente",
},
});

const response = await request(app)
.patch(`/finance/updateBankAccount/${null}`) // Atualize o caminho da rota
.send({ name: "Conta Atualizada" });

console.log("Update Response:", response.body); // Adicione um log para depuração

expect(response.status).toBe(400);
});

it("should delete a bank account", async () => {
const newAccount = await request(app)
.post("/finance/createBankAccount") // Atualize o caminho da rota
Expand All @@ -150,4 +208,21 @@
expect(response.status).toBe(200);
expect(response.body.message).toBe("Conta deletada com sucesso");
});
it("should delete a bank account", async () => {
const response = await request(app).delete(
`/finance/deleteBankAccount/${null}`
); // Atualize o caminho da rota

expect(response.status).toBe(500);
});

it("should return 404 if bank account is not found by ID", async () => {
const invalidId = new mongoose.Types.ObjectId(); // Gerar um ID válido, mas que não está no banco

const response = await request(app).get(
`/finance/getBankAccountbyId/${invalidId}`
);

expect(response.status).toBe(404);
});
});
57 changes: 57 additions & 0 deletions src/__tests__/suppllierFormController.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,36 @@ describe("Supplier Form Controller Tests", () => {
supplierId = res.body._id;
});

it("should fail create a new supplier form without name", async () => {
const res = await request(app)
.post("/SupplierForm/create")
.send({
supplierData: {
nome: "",
tipoPessoa: "",
cpfCnpj: "",
statusFornecedor: "",
naturezaTransacao: "",
email: "",
nomeContato: "",
celular: "",
telefone: "",
cep: "",
cidade: "",
uf_endereco: "",
logradouro: "",
complemento: "",
nomeBanco: "",
agencia: "",
numeroBanco: "",
dv: "",
chavePix: "",
},
});

expect(res.status).toBe(400);
});

it("should get all supplier forms", async () => {
const res = await request(app).get("/SupplierForm");

Expand All @@ -90,6 +120,12 @@ describe("Supplier Form Controller Tests", () => {
expect(res.body).toHaveProperty("nome", "Test Supplier");
});

it("should fail get a supplier form without ID", async () => {
const res = await request(app).get(`/SupplierForm/${null}`);

expect(res.status).toBe(400);
});

it("should update a supplier form by ID", async () => {
const res = await request(app)
.patch(`/SupplierForm/update/${supplierId}`)
Expand All @@ -99,6 +135,14 @@ describe("Supplier Form Controller Tests", () => {
expect(res.body).toHaveProperty("nome", "Updated Supplier");
});

it("should fail to update a supplier form without ID", async () => {
const res = await request(app)
.patch(`/SupplierForm/update/${null}`)
.send({ supplierData: { nome: "Updated Supplier" } });

expect(res.status).toBe(400);
});

it("should delete a supplier form by ID", async () => {
const res = await request(app).delete(
`/SupplierForm/delete/${supplierId}`
Expand All @@ -111,4 +155,17 @@ describe("Supplier Form Controller Tests", () => {
);
expect(checkSupplier.status).toBe(404);
});

it("should fail to delete a supplier form without ID", async () => {
const res = await request(app).delete(
`/SupplierForm/delete/${supplierId}`
);

expect(res.status).toBe(200);

const checkSupplier = await request(app).get(
`/SupplierForm/delete/${supplierId}`
);
expect(checkSupplier.status).toBe(404);
});
});
138 changes: 138 additions & 0 deletions src/__tests__/utils.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
const { validator } = require("../Util/utils");

describe("Supplier Data Validator", () => {
it("should return an error for invalid nome", () => {
const result = validator({ nome: "" });
expect(result).toBe("Nome ou Razão social inválidos");
});

it("should return an error for invalid tipoPessoa", () => {
const result = validator({ nome: "Valid Name", tipoPessoa: "Invalid" });
expect(result).toBe("Tipo de pessoa inválida");
});

it("should return an error for invalid CPF", () => {
const result = validator({
nome: "Valid Name",
tipoPessoa: "Jurídica",
cpfCnpj: "123.456.789-10",
});
expect(result).toBe("CPF ou CNPJ inválido");
});

it("should return an error for invalid CNPJ", () => {
const result = validator({
nome: "Valid Name",
tipoPessoa: "Física",
cpfCnpj: "12.345.678/0001-99",
});
expect(result).toBe("CPF ou CNPJ inválido");
});

it("should return an error for invalid statusFornecedor", () => {
const result = validator({
nome: "Valid Name",
statusFornecedor: "Invalid",
});
expect(result).toBe("Status de fornecedor inválido");
});

it("should return an error for invalid naturezaTransacao", () => {
const result = validator({
nome: "Valid Name",
naturezaTransacao: "Invalid",
});
expect(result).toBe("Tipo de transação inválida");
});

it("should return an error for invalid email", () => {
const result = validator({ nome: "Valid Name", email: "invalidemail" });
expect(result).toBe("E-mail inválido");
});

it("should return an error for invalid nomeContato", () => {
const result = validator({ nome: "Valid Name", nomeContato: 12345 });
expect(result).toBe("Nome de contato inválido");
});

it("should return an error for invalid celular", () => {
const result = validator({ nome: "Valid Name", celular: "1234567890" });
expect(result).toBe("Número de celular inválido");
});

it("should return an error for invalid telefone", () => {
const result = validator({ nome: "Valid Name", telefone: "12345678" });
expect(result).toBe("Número de telefone inválido");
});

it("should return an error for invalid cep", () => {
const result = validator({ nome: "Valid Name", cep: "12345-6789" });
expect(result).toBe("Cep inválido");
});

it("should return an error for invalid cidade", () => {
const result = validator({ nome: "Valid Name", cidade: 12345 });
expect(result).toBe("Cidade inválida");
});

it("should return an error for invalid uf_endereco", () => {
const result = validator({ nome: "Valid Name", uf_endereco: "XX" });
expect(result).toBe("UF inválida");
});

it("should return an error for invalid logradouro", () => {
const result = validator({ nome: "Valid Name", logradouro: "123" });
expect(result).toBe(
"Logradouro inválido. Deve conter entre 5 e 100 caracteres."
);
});

it("should return an error for invalid complemento", () => {
const result = validator({ nome: "Valid Name", complemento: 12345 });
expect(result).toBe("Complemento inválido");
});

it("should return an error for invalid agencia", () => {
const result = validator({ nome: "Valid Name", agencia: 12345 });
expect(result).toBe("Agência inválida");
});

it("should return an error for invalid numeroBanco", () => {
const result = validator({ nome: "Valid Name", numeroBanco: "ABC" });
expect(result).toBe("Número inválido");
});

it("should return an error for invalid dv", () => {
const result = validator({ nome: "Valid Name", dv: "ABC" });
expect(result).toBe("DV inválido");
});

it("should return an error for invalid chavePix", () => {
const result = validator({ nome: "Valid Name", chavePix: 12345 });
expect(result).toBe("Chave Pix inválida");
});

it("should return null for valid data", () => {
const result = validator({
nome: "Valid Name",
tipoPessoa: "Física",
cpfCnpj: "123.456.789-10",
statusFornecedor: "Ativo",
naturezaTransacao: "Receita",
email: "[email protected]",
nomeContato: "Valid Contact",
celular: "(12) 34567-8910",
telefone: "(12) 3456-7890",
cep: "12345-678",
cidade: "Valid City",
uf_endereco: "SP",
logradouro: "Rua dos Validos, 123",
complemento: "Apto 45",
agencia: "1234",
numeroBanco: "5678",
dv: "9",
chavePix: "validpixkey",
});
expect(result).toBeNull();
});
});
1 change: 0 additions & 1 deletion src/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ routes.post(
"/finance/createBankAccount",
bankAccountController.createBankAccount
);
routes.get("/finance/bankAccount", bankAccountController.getBankAccount);
routes.get(
"/finance/bankAccount/:id",
bankAccountController.getBankAccountbyId
Expand Down
Loading