You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/content/4/ptbr/part4b.md
+46-46Lines changed: 46 additions & 46 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -200,7 +200,7 @@ e acrescentar nas definições do Jest no <i>package.json</i> o seguinte:
200
200
}
201
201
```
202
202
203
-
Outro erro que pode aparecer para você nos seus testes:
203
+
Outro erro que pode aparecer para você nos seus testes é se a execução deles demorar mais do que 5 segundos (5000ms), que é o tempo padrão do Jest para <i>timeout</i>. Isso pode ser resolvido adicionando um terceiro parâmetro na função test:
204
204
205
205
```js
206
206
test('notes are returned as json', async () => {
@@ -211,9 +211,9 @@ test('notes are returned as json', async () => {
211
211
}, 100000)
212
212
```
213
213
214
-
This third parameter sets the timeout to 100000 ms. A long timeout ensures that our test won't fail due to the time it takes to run. (A long timeout may not be what you want for tests based on performance or speed, but this is fine for our example tests).
214
+
Esse terceiro parâmetro configura o <i>timeout</i> para 100 segundos (100000ms). Um tempo longo garantirá que seu teste não falhe em razão do tempo que ele leva para executar. (Um <i>timeout</i> muito longo talvez não seja o que você queira para testes baseados em performance ou velocidade, mas para este nosso exemplo é ok).
215
215
216
-
One tiny but important detail: at the [beginning](/en/part4/structure_of_backend_application_introduction_to_testing#project-structure) of this part we extracted the Express application into the <i>app.js</i> file, and the role of the <i>index.js</i> file was changed to launch the application at the specified port with Node's built-in <i>http</i> object:
216
+
Um detalhe importante é o seguinte: no [começo](/ptbr/part4/estrutura_de_uma_aplicacao_back_end_introducao_a_testes#estrutura-do-projeto) dessa parte, nós extraímos a aplicação Express no arquivo <i>app.js</i>, e o papel do arquivo <i>index.js</i> foi alterado para iniciar a aplicação na porta especificada com o objeto <i>http</i> integrado do Node:
217
217
218
218
```js
219
219
constapp=require('./app') // the actual Express app
The tests only use the express application defined in the <i>app.js</i> file:
228
+
Os testes somente utilizam a aplicação express definida no arquivo <i>app.js</i>:
229
229
230
230
```js
231
231
constmongoose=require('mongoose')
@@ -237,15 +237,15 @@ const api = supertest(app) // highlight-line
237
237
// ...
238
238
```
239
239
240
-
The documentation for supertest says the following:
240
+
A documentação do <i>supertest</i> informa o seguinte:
241
241
242
-
> <i>if the server is not already listening for connections then it is bound to an ephemeral port for you so there is no need to keep track of ports.</i>
242
+
> <i>se o servidor ainda não estiver ouvindo as conexões, então ele estará ligado em uma porta efêmera, logo não há necessidade de acompanhar as portas.</i>
243
243
244
-
In other words, supertest takes care that the application being tested is started at the port that it uses internally.
244
+
Em outras palavras, o <i>supertest</i> se responsabiliza de iniciar a aplicação que está sendo testada na porta que está em uso internamente.
245
245
246
-
Let's add two notes to the test database using the _mongo.js_program (here we must remember to switch to the correct database url).
246
+
Vamos adicionar duas notas no banco de dados de teste, usando o _mongo.js_(lembre-se de mudar para a url correta do banco de dados).
247
247
248
-
Let's write a few more tests:
248
+
Vamos escrever alguns testes a mais:
249
249
250
250
```js
251
251
test('there are two notes', async () => {
@@ -261,19 +261,19 @@ test('the first note is about HTTP methods', async () => {
261
261
})
262
262
```
263
263
264
-
Both tests store the response of the request to the_response_ variable, and unlike the previous test that used the methods provided by _supertest_for verifying the status code and headers, this time we are inspecting the response data stored in <i>response.body</i> property. Our tests verify the format and content of the response data with the [expect](https://jestjs.io/docs/expect#expectvalue) method of Jest.
264
+
Ambos os testes armazenam a resposta da requisição na variáveis_response_, e diferente da versão anterior do teste que utilizava o método provido pelo _supertest_para verificar o código de status e o cabeçalho, desta vez nós estamos inspecionando os dados de resposta armazenados na propriedade <i>response.body</i>. Nossos testes verificam o formato e o conteúdo dos dados da resposta com o método do Jest [expect](https://jestjs.io/pt-BR/docs/expect).
265
265
266
-
The benefit of using the async/await syntax is starting to become evident. Normally we would have to use callback functions to access the data returned by promises, but with the new syntax things are a lot more comfortable:
266
+
O benefício de usar a sintaxe async/await começa a ficar evidente. Normalmente, teríamos que usar funções de retorno de chamada para acessar os dados retornados pelas promessas, mas, com a nova sintaxe, as coisas estão muito mais simples:
267
267
268
268
```js
269
269
constresponse=awaitapi.get('/api/notes')
270
270
271
-
//execution gets here only after the HTTP request is complete
272
-
//the result of HTTP request is saved in variable response
271
+
//a execução chega aqui somente após a requisição HTTP estar completa
272
+
//o resultado da requisição HTTP é salva na variável response
273
273
expect(response.body).toHaveLength(2)
274
274
```
275
275
276
-
The middleware that outputs information about the HTTP requests is obstructing the test execution output. Let us modify the logger so that it does not print to the console in test mode:
276
+
O <i>middleware</i> que exibe informações sobre as solicitações HTTP está obstruindo a saída da execução do teste. Vamos modificar o logger para que ele não imprima no console no modo de teste:
277
277
278
278
```js
279
279
constinfo= (...params) => {
@@ -297,13 +297,13 @@ module.exports = {
297
297
}
298
298
```
299
299
300
-
### Initializing the database before tests
300
+
### Inicializando o banco de dados antes dos testes
301
301
302
-
Testing appears to be easy and our tests are currently passing. However, our tests are bad as they are dependent on the state of the database, that now happens to have two notes. To make our tests more robust, we have to reset the database and generate the needed test data in a controlled manner before we run the tests.
302
+
Testar parece ser fácil e atualmente nossos testes estão passando. No entanto, nossos testes são ruins, uma vez que dependem do estado do banco de dados, que agora tem duas notas. Para tornar nossos testes mais robustos, devemos redefinir o banco de dados e gerar os dados de teste necessários de maneira controlada antes de executarmos os testes.
303
303
304
-
Our tests are already using the [afterAll](https://jestjs.io/docs/api#afterallfn-timeout)function of Jest to close the connection to the database after the tests are finished executing. Jest offers many other [functions](https://jestjs.io/docs/setup-teardown)that can be used for executing operations once before any test is run or every time before a test is run.
304
+
Nosso código já está utilizando a função do Jest [afterAll](https://jestjs.io/pt-BR/docs/api#afterallfn-timeout)para encerrar a conexão com o banco de dados após a conclusão da execução dos testes. O Jest oferece muitas outras [funções](https://jestjs.io/pt-BR/docs/setup-teardown)que podem ser utilizadas para executar operações uma vez antes de executar qualquer teste ou antes da execução de cada teste.
305
305
306
-
Let's initialize the database <i>before every test</i> with the [beforeEach](https://jestjs.io/docs/en/api.html#beforeeachfn-timeout) function:
306
+
Vamos inicializar o banco de dados <i>antes de cada teste</i> com a função [beforeEach](https://jestjs.io/docs/en/api.html#beforeeachfn-timeout):
307
307
308
308
```js
309
309
constmongoose=require('mongoose')
@@ -341,9 +341,9 @@ beforeEach(async () => {
341
341
// ...
342
342
```
343
343
344
-
The database is cleared out at the beginning, and after that, we save the two notes stored in the _initialNotes_array to the database. By doing this, we ensure that the database is in the same state before every test is run.
344
+
O banco de dados é apagado logo no início, após isso salvamos no banco as duas notas armazenadas no <i>array</i> initialNotes. Fazendo isso, garantimos que o banco de dados esteja no mesmo estado antes da execução de cada teste.
345
345
346
-
Let's also make the following changes to the last two tests:
346
+
Vamos fazer também algumas alterações nos dois últimos testes:
347
347
348
348
```js
349
349
test('all notes are returned', async () => {
@@ -365,54 +365,54 @@ test('a specific note is within the returned notes', async () => {
365
365
})
366
366
```
367
367
368
-
Pay special attention to the expect in the latter test. The <code>response.body.map(r => r.content)</code> command is used to create an array containing the content of every note returned by the API. The [toContain](https://jestjs.io/docs/expect#tocontainitem)method is used for checking that the note given to it as a parameter is in the list of notes returned by the API.
368
+
Dê uma atenção especial no expect do último teste. O comando <code>response.body.map(r => r.content)</code> é utilizado para criar um array contendo o que está no <i>content</i> de cada nota retornada pela API. O método [toContain](https://jestjs.io/docs/expect#tocontainitem)é utilizado para checar se a nota passada como parâmetro está na lista de notas retornada pela API.
369
369
370
-
### Running tests one by one
370
+
### Executando os testes um por um
371
371
372
-
The _npm test_command executes all of the tests for the application. When we are writing tests, it is usually wise to only execute one or two tests. Jest offers a few different ways of accomplishing this, one of which is the[only](https://jestjs.io/docs/en/api#testonlyname-fn-timeout) method. If tests are written across many files, this method is not great.
372
+
O comando _npm test_executa todos os testes da aplicação. Quando estamos escrevendo testes, normalmente é sábio executar um ou dois testes. O Jest oferece algumas formas diferentes de fazer isso, uma delas é o método[only](https://jestjs.io/docs/en/api#testonlyname-fn-timeout). Se os testes estiverem escritos em vários arquivos, esse método não é muito bom.
373
373
374
-
A better option is to specify the tests that need to be run as parameters of the <i>npm test</i> command.
374
+
Uma opção melhor é especificar os testes que precisam ser executados como parâmetros do comando <i>npm test</i>.
375
375
376
-
The following command only runs the tests found in the <i>tests/note_api.test.js</i> file:
376
+
O comando a seguir somente executa os testes encontrados no arquivo <i>tests/note_api.test.js</i>:
377
377
378
378
```js
379
379
npm test -- tests/note_api.test.js
380
380
```
381
381
382
-
The <i>-t</i> option can be used for running tests with a specific name:
382
+
A opção <i>-t</i> pode ser utilizada para executar testes com um nome específico:
383
+
383
384
384
385
```js
385
386
npm test ---t "a specific note is within the returned notes"
386
387
```
387
388
388
-
The provided parameter can refer to the name of the test or the describe block. The parameter can also contain just a part of the name. The following command will run all of the tests that contain <i>notes</i> in their name:
389
+
O parâmetros informado pode referenciar o nome do teste ou o bloco <i>describe</i>. O parâmetro também pode conter somente parte do nome. O comando a seguir vai executar todos os testes que contenha <i>notes</i> em seu nome
389
390
390
391
```js
391
392
npm test ---t 'notes'
392
393
```
393
394
394
-
**Obs.:**: When running a single test, the mongoose connection might stay open if no tests using the connection are run.
395
-
The problem might be because supertest primes the connection, but Jest does not run the afterAll portion of the code.
395
+
**Obs.:**: Ao executar um único teste, a conexão mongoose pode permanecer aberta se nenhum teste usando a conexão for executado. O problema pode ser porque o <i>supertest</i> prepara a conexão, mas o Jest não executa a parte <i>afterAll</i> do código.
396
396
397
397
### async/await
398
398
399
-
Before we write more tests let's take a look at the_async_and_await_ keywords.
399
+
Antes de escrevermos mais testes, vamos dar uma olhada nas palavras-chave_async_e_await_.
400
400
401
-
The async/await syntax that was introduced in ES7 makes it possible to use <i>asynchronous functions that return a promise</i> in a way that makes the code look synchronous.
401
+
A sintaxe async/await que foi introduzida no ES7, torna possível o uso de <i>funções assíncronas que retornam uma promessa</i> de um jeito que parece com código síncrono.
402
402
403
-
As an example, the fetching of notes from the database with promises looks like this:
403
+
Como um exemplo, a busca das notas do banco de dados utilizando promessas é assim:
404
404
405
405
```js
406
406
Note.find({}).then(notes=> {
407
407
console.log('operation returned the following notes', notes)
408
408
})
409
409
```
410
410
411
-
The _Note.find()_method returns a promise and we can access the result of the operation by registering a callback function with the _then_ method.
411
+
O método _Note.find()_retorna uma promessa e podemos acessar o resultado da operação registrando a função <i>callback</i> com o método _then()_.
412
412
413
-
All of the code we want to execute once the operation finishes is written in the callback function. If we wanted to make several asynchronous function calls in sequence, the situation would soon become painful. The asynchronous calls would have to be made in the callback. This would likely lead to complicated code and could potentially give birth to a so-called[callback hell](http://callbackhell.com/).
413
+
Todo o código que queremos executar quando a operação termina está escrito na função <i>callback</i>. Se quisermos fazer diversas chamadas de funções assíncronas em sequência, a situação logo ficará complicada. As chamadas assíncronas seriam feitas na função <i>callback</i>. Isso resultaria em um código complicado e provavelmente surgiria o chamado[callback hell](http://callbackhell.com/).
414
414
415
-
By [chaining promises](https://javascript.info/promise-chaining) we could keep the situation somewhat under control, and avoid callback hell by creating a fairly clean chain of _then_ method calls. We have seen a few of these during the course. To illustrate this, you can view an artificial example of a function that fetches all notes and then deletes the first one:
415
+
[Encadeando promessas](https://javascript.info/promise-chaining), nós conseguiríamos manter a situação sob controle e evitar o <i>callback hell</i> ao criar uma cadeia bem limpa de chamadas de métodos _then()_. Vimos alguns desses durante o curso. Para ilustrar, você pode ver um exemplo de uma função que busca todas as notas e, em seguida, exclui a primeira delas:
416
416
417
417
```js
418
418
Note.find({})
@@ -421,25 +421,25 @@ Note.find({})
421
421
})
422
422
.then(response=> {
423
423
console.log('the first note is removed')
424
-
//more code here
424
+
//mais código aqui
425
425
})
426
426
```
427
427
428
-
The then-chain is alright, but we can do better. The[generator functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator)introduced in ES6 provided a [clever way](https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/async%20%26%20performance/ch4.md#iterating-generators-asynchronously)of writing asynchronous code in a way that "looks synchronous". The syntax is a bit clunky and not widely used.
428
+
A cadeia de métodos _then()_ é ok, mas podemos fazer melhor do que isso. As[generator functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator)introduzidas no ES6 trazem um [jeito inteligente](https://github.com/getify/You-Dont-Know-JS/blob/1st-ed/async%20%26%20performance/ch4.md#iterating-generators-asynchronously)de escrever código assíncrono de uma forma que "parece síncrono". A sintaxe é um pouco estranha e não é muito utilizada.
429
429
430
-
The _async_and_await_keywords introduced in ES7 bring the same functionality as the generators, but in an understandable and syntactically cleaner way to the hands of all citizens of the JavaScript world.
430
+
As palavras-chave _async_e_await_ introduzidas no ES7 trazem a mesma funcionalidade dos <i>generators</i>, mas de uma maneira compreensível e sintaticamente mais limpa para todos os cidadãos do mundo JavaScript.
431
431
432
-
We could fetch all of the notes in the database by utilizing the [await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await)operator like this:
432
+
Poderíamos buscar todas as notas no banco de dados utilizando o operador [await](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await)dessa forma:
433
433
434
434
```js
435
435
constnotes=awaitNote.find({})
436
436
437
437
console.log('operation returned the following notes', notes)
438
438
```
439
439
440
-
The code looks exactly like synchronous code. The execution of code pauses at <em>const notes = await Note.find({})</em> and waits until the related promise is <i>fulfilled</i>, and then continues its execution to the next line. When the execution continues, the result of the operation that returned a promise is assigned to the_notes_ variable.
440
+
O código parece idêntico a um código síncrono. A execução do código pausa em <em>const notes = await Note.find({})</em> e aguarda até que a promessa seja <i>completada (fulfilled)</i>, então continua a sua execução na próxima linha. Quando a execução continua, o resultado da operação que retornou a promessa é atribuído à variável_notes_.
441
441
442
-
The slightly complicated example presented above could be implemented by using await like this:
442
+
O exemplo um pouco complicado apresentado acima poderia ser implementado usando <i>await</i> assim:
Thanks to the new syntax, the code is a lot simpler than the previous then-chain.
451
+
Graças à nova sintaxe, o código é muito mais simples do que a cadeia de _then()_ anterior.
452
452
453
-
There are a few important details to pay attention to when using async/await syntax. To use the await operator with asynchronous operations, they have to return a promise. This is not a problem as such, as regular asynchronous functions using callbacks are easy to wrap around promises.
453
+
Existem alguns detalhes importantes para prestar atenção ao usar a sintaxe async/await. Para usar o operador await com operações assíncronas, elas precisam retornar uma promessa. Isso não é um problema em si, já que as funções assíncronas regulares que usam <i>callbacks</i> são fáceis de envolver em promessas.
454
454
455
-
The await keyword can't be used just anywhere in JavaScript code. Using await is possible only inside of an [async](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) function.
455
+
A palavra-chave await não pode ser utilizada em qualquer lugar do código JavaScript. Somente é possível usar o await dentro de uma função [assíncrona (async)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function).
456
456
457
-
This means that in order for the previous examples to work, they have to be using async functions. Notice the first line in the arrow function definition:
457
+
Isso significa que para os exemplos anteriores funcionarem, é preciso que estejam em funcções assíncronas. Note a primeira linha da definição da <i>arrow function</i>:
0 commit comments