Skip to content

dorminhoco test + resolution #17

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

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
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
19 changes: 19 additions & 0 deletions programming-basics/dorminhoco/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
const dreamList = [
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ainda estou pensando em como fazer com a lista sem aleatoriaedade

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

acho que fica mais fácil. talvez, vamos tentar moldar a ordem do problema de uma vez antes de ir para implementação

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

aleatoriedade é o que torna os testes mais fracos, dado que você pode ter resultados diferentes para cada vez que vc rodar os testes, acho que seria bom simplificar essa implementação mesmo

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Uma possibilidade é mockar a função 'Math.random()'

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

muito bem, vou implementar, junto com os testes dos caminhos feios aushda <3

'Ovelhas astronautas',
'Tava jogando mesmo',
'Sonhei com código',
'Mozão',
];

const randomDream = (dreams) =>
dreams[Math.floor(Math.random() * dreams.length)];

const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));

export const dorminhoco = async (milliseconds, dreamList) => {

await sleep(milliseconds)

const dream = randomDream(dreamList);
return dream;
Comment on lines +14 to +18
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
await sleep(milliseconds)
const dream = randomDream(dreamList);
return dream;
if (Array.isArray(dreamList))
return // early return to avoid extra processing
await sleep(milliseconds)
return randomDream(dreamList)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Simplificando a implementação

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

};
47 changes: 47 additions & 0 deletions programming-basics/dorminhoco/test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { dorminhoco } from './main';
const dreamMock = ['não lembro do sonho', 'test', 'test2' ];

describe('Testes - Dominhoco', () => {
beforeEach(() => {
jest.clearAllMocks();
jest.restoreAllMocks();
jest.spyOn(global.Math, 'random').mockReturnValue(0);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Boa, mandou bem no mock!

Uma dúvida: precisamos de dar spyOn sempre antes de cada test case? Ou podemos usá-lo apenas uma vez e aceitar que o jest.clearAllMocks() vai limpar o mock pra gente?

});

it(`checa retorno com array vazio como entrada`, () => {
return dorminhoco(42, []).then((dream) => {
expect(dream).toBe(undefined);
});
});

it(`resultado deve ser uma string`, () => {
return dorminhoco(42, dreamMock).then((dream) => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Acho que seria mais elegante usar async/await para lidar com promises

expect(typeof dream).toBe('string');
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Não precisamos validar o type, dado que estamos validando o valor + tipo logo abaixo

expect(dream).toBe(dreamMock[0]);
});
});

it(`checa retorno com entrada falsa`, () => {
return dorminhoco(42, false).then((dream) => {
expect(dream).toBe(undefined);
});
});

it(`checa retorno com entrada como numero`, () => {
return dorminhoco(42, 42).then((dream) => {
expect(dream).toBe(undefined);
});
});

it(`checa retorno com entrada como string`, () => {
return dorminhoco(42, 'nao sou um array').then((dream) => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

me parece estranho rodar com uma string. Não deveriamos rodar apenas com array? Mesmo o JS tratando Array como String, acho que seria melhor nao rodar para strings

# input:
42 "minha string'

# output
undefined

expect(dream).toBe('n');
});
});

it(`espera que setTimeout seja chamado com uma função`, async () => {
jest.useFakeTimers();
dorminhoco(42, dreamMock);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

dado que o dominhoco é uma promise, precisamos de dar await aqui para aguardar a execução. Do jeito que está vai passar por causa do asset feito abaixo, que só valida se setTimeout foi chamado, mas num teste real, precisamos aguardar as promisses se resolverem antes de validar o retorno

expect(setTimeout).toBeCalledWith(expect.any(Function), 42);
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

função chamada com undefined, não entendi o processo

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

seu teste não é async, acredito que isto está impactando sua leitura

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

faz mt sentido :D
vou implementar!

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1

});
});
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Não temos casos de testes com listas vazias.

quando fazemos unit teste temos que validar caminhos felizes e caminhos tristes, como por exemplo:

  • lista vazia
  • string no lugar da lista
  • lista undefined
  • so on

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Acho válido, mas estou tentando testar com o node assim:
dorminhoco(42, [])
e dá isso:
SyntaxError: Unexpected token 'export'

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

node por padrão não reconhece o exoprt, precisamos do babel para tal. No entanto, o Jest deveria lidar com isso pra gente.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

O ideal é rodar com jest e ir testando