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

feat: adiciona código de erro semântico em casos de ceps mal formatados #38

Merged
merged 8 commits into from Jun 10, 2020
11 changes: 10 additions & 1 deletion pages/api/cep/v1/[cep].js
Expand Up @@ -32,8 +32,17 @@ async function Cep(request, response) {
response.json(cepResult);

} catch (error) {

if (error.name === 'CepPromiseError') {
response.status(404);
switch(error.type) {
case "validation_error":
paulo-santana marked this conversation as resolved.
Show resolved Hide resolved
response.status(400);
break;
case "service_error":
paulo-santana marked this conversation as resolved.
Show resolved Hide resolved
response.status(404);
break;
}

response.json(error);
return;
}
Expand Down
54 changes: 38 additions & 16 deletions tests/cep-v1.test.js
Expand Up @@ -25,24 +25,46 @@ describe('/cep/v1 (E2E)', () => {
});
});

test.skip('Utilizando um CEP inexistente: 00000000', async () => {
// O endpoint /cep/v1 está retornando 404 independente
// do CEP não existir ou ele não ser válido. Podemos melhorar
// esse comportamento fazendo uma diferenciação no Status do
// response para quando for um type "validation_error" ou "service_error"

// Nesse caso aqui seria um "service_error":
// "Todos os serviços de CEP retornaram erro."
test('Utilizando um CEP inexistente: 00000000', async () => {
expect.assertions(2);
const requestUrl = `${server.getUrl()}/api/cep/v1/00000000`;

try {
await axios.get(requestUrl);

} catch (error) {
const { response } = error;

expect(response.status).toBe(404);
expect(response.data).toMatchObject({
name: 'CepPromiseError',
message: 'Todos os serviços de CEP retornaram erro.',
type: 'service_error'
});
}
});

test.skip('Utilizando um CEP inválido: 999999999999999', async () => {
// O endpoint /cep/v1 está retornando 404 independente
// do CEP não existir ou ele não ser válido. Podemos melhorar
// esse comportamento fazendo uma diferenciação no Status do
// response para quando for um type "validation_error" ou "service_error"

// Nesse caso aqui seria um "validation_error":
// "CEP deve conter exatamente 8 caracteres."
test('Utilizando um CEP inválido: 999999999999999', async () => {
expect.assertions(2);
const requestUrl = `${server.getUrl()}/api/cep/v1/999999999999999`;

try {
await axios.get(requestUrl);

} catch (error) {
const { response } = error;

expect(response.status).toBe(400);
expect(response.data).toEqual({
name: "CepPromiseError",
message: "CEP deve conter exatamente 8 caracteres.",
type: "validation_error",
errors: [{
message: "CEP informado possui mais do que 8 caracteres.",
service: "cep_validation"
}]
});
}
});

});