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: 1-js/03-code-quality/01-debugging-chrome/article.md
+1-40Lines changed: 1 addition & 40 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -38,11 +38,7 @@ Se pressionarmos `key:Esc`, um terminal (*Console*) se abrirá abaixo. Assim per
38
38
39
39
Depois de uma instrução ser executada, o resultado será mostrado logo a seguir.
40
40
41
-
<<<<<<< HEAD
42
41
Por exemplo, a instrução `1+2` resultará em `3`, enquanto a chamada de função `hello("debugger")` não retornará nada, assim tendo como resultado `undefined`:
43
-
=======
44
-
For example, here `1+2` results in `3`, while the function call `hello("debugger")` returns nothing, so the result is `undefined`:
45
-
>>>>>>> d78b01e9833009fab534462e05c03cffc51bf0e3
46
42
47
43

48
44
@@ -66,22 +62,13 @@ Uma lista de *breakpoints* sempre estará disponível no painel à direita. Muit
66
62
- Remover o breakpoint, clicando com o botão direito do mouse e selecionando *Remove*.
67
63
- ...E assim por diante.
68
64
69
-
<<<<<<< HEAD
70
65
```smart header="*Breakpoints* condicionais"
71
66
*Clicar com o botão direito do mouse* sobre um número de linha permite a criação de um *breakpoint condicional* o qual será ativado apenas quando a expressão inserida for verdadeira.
72
-
=======
73
-
```smart header="Conditional breakpoints"
74
-
*Right click* on the line number allows to create a *conditional* breakpoint. It only triggers when the given expression, that you should provide when you create it, is truthy.
75
-
>>>>>>> d78b01e9833009fab534462e05c03cffc51bf0e3
76
67
77
68
É prático quando precisamos de suspender a execução apenas para valores determinados de certa variável ou para parâmetros específicos numa função.
78
69
```
79
70
80
-
<<<<<<< HEAD
81
-
## O comando *debugger*
82
-
=======
83
-
## The command "debugger"
84
-
>>>>>>> d78b01e9833009fab534462e05c03cffc51bf0e3
71
+
## O comando "debugger"
85
72
86
73
Podemos também suspender o código utilizando o comando `debugger`, desta forma:
87
74
@@ -97,13 +84,9 @@ function hello(name) {
97
84
}
98
85
```
99
86
100
-
<<<<<<< HEAD
101
87
Este comando só irá funcionar quando a interface de ferramentas de desenvolvedor do navegador estiver aberta, caso contrário, será ignorado.
102
88
103
89
## Pause e dê uma olhada
104
-
=======
105
-
Such command works only when the development tools are open, otherwise the browser ignores it.
106
-
>>>>>>> d78b01e9833009fab534462e05c03cffc51bf0e3
107
90
108
91
No nosso exemplo, a função `hello()` é chamada durante o carregamento da página, assim a forma mais fácil para ativar o *debugger* (depois de termos colocado os *breakpoints*) seria recarregar a página. Desta forma, vamos pressionar `key:F5` (Windows, Linux) ou `key:Cmd+R` (Mac).
109
92
@@ -115,11 +98,7 @@ Por favor, abra as secções de *dropdown* informacionais à direita (apontadas
115
98
116
99
1.**`Watch` -- mostra valores atuais das expressões.**
117
100
118
-
<<<<<<< HEAD
119
101
É possível clicar no `+` e inserir uma expressão. O *debugger* mostrará o valor da expressão e continuará recalculando-a ao longo do processo de execução.
120
-
=======
121
-
You can click the plus `+` and input an expression. The debugger will show its value, automatically recalculating it in the process of execution.
122
-
>>>>>>> d78b01e9833009fab534462e05c03cffc51bf0e3
123
102
124
103
2.**`Call Stack` -- mostra a sequência de chamadas de funções aninhadas.**
125
104
@@ -154,21 +133,12 @@ Existem botões para isso no topo do painel direito. Vamos interagir com eles.
154
133
155
134
Continuando a clicar nele, passará por todas as instruções do programa, uma por uma.
156
135
157
-
<<<<<<< HEAD
158
136
<spanclass="devtools"style="background-position:-62px-192px"></span> -- "Step over": execute o próximo comando, *mas não vá para dentro de uma função*, atalho `key:F10`.
159
137
: Similar ao comando "Step" anterior mas com um comportamento diferente se a próxima instrução for uma chamada de função. Isto é: não uma incorporada (*built-in*), como `alert`, mas uma função nossa.
160
138
161
139
O comando "Step", vai para dentro dessa função e suspende a execução na sua primeira linha, ao contrário de "Step over" que executa essa chamada de função aninhada de forma invisível para nós, pulando todo seu funcionamento interno.
162
140
163
141
É feita uma pausa na execução imediatamente depois dessa função.
164
-
=======
165
-
<spanclass="devtools"style="background-position:-62px-192px"></span> -- "Step over": run the next command, but *don't go into a function*, hotkey `key:F10`.
166
-
: Similar to the previous "Step" command, but behaves differently if the next statement is a function call (not a built-in, like `alert`, but a function of our own).
167
-
168
-
If we compare them, the "Step" command goes into a nested function call and pauses the execution at its first line, while "Step over" executes the nested function call invisibly to us, skipping the function internals.
169
-
170
-
The execution is then paused immediately after that function call.
171
-
>>>>>>> d78b01e9833009fab534462e05c03cffc51bf0e3
172
142
173
143
É util quando não se está interessado em ver o que acontece dentro da chamada de uma função.
174
144
@@ -183,13 +153,8 @@ Existem botões para isso no topo do painel direito. Vamos interagir com eles.
183
153
<spanclass="devtools"style="background-position:-61px-74px"></span> -- ativar/desativar todos os *breakpoints*.
184
154
: Esse botão não move a execução. Simplesmente ativa/desativa *breakpoints* em conjunto.
185
155
186
-
<<<<<<< HEAD
187
156
<spanclass="devtools"style="background-position:-90px-146px"></span> -- ativar/desativar a pausa automática em caso de erro.
188
157
: Quando ativo e as ferramentas do desenvolvedor abertas, um erro no código automáticamente suspende a execução do código. Assim permitindo a análise de variáveis para entender o que ocorreu de errado. Desta forma, se o código falhar por um erro, é possível abrir o *debugger*, ativar esta opção e recarregar a página afim de se observar onde e em que contexto a falha ocorreu.
189
-
=======
190
-
<spanclass="devtools"style="background-position:-90px-146px"></span> -- enable/disable automatic pause in case of an error.
191
-
: When enabled, if the developer tools is open, an error during the script execution automatically pauses it. Then we can analyze variables in the debugger to see what went wrong. So if our script dies with an error, we can open debugger, enable this option and reload the page to see where it dies and what's the context at that moment.
192
-
>>>>>>> d78b01e9833009fab534462e05c03cffc51bf0e3
193
158
194
159
```smart header="Continue até aqui"
195
160
Ao clicar com o botão direito do mouse sobre uma linha de código, abre-se o menu de contexto com uma ótima opção chamada "Continue até aqui" (*Continue to here*).
@@ -221,11 +186,7 @@ Como podemos ver, existem três formas principais para pausar a execução de um
221
186
2. As instruções `debugger`.
222
187
3. Um erro (se as ferramentas do desenvolvedor [*dev tools*] estiverem abertas, e o botão <spanclass="devtools"style="background-position:-90px-146px"></span> estiver "ativo").
223
188
224
-
<<<<<<< HEAD
225
189
Enquanto suspenso, podemos depurar erros - examinar variáveis e rastear o código para ver que parte da execução ocorre com erros.
226
-
=======
227
-
When paused, we can debug: examine variables and trace the code to see where the execution goes wrong.
228
-
>>>>>>> d78b01e9833009fab534462e05c03cffc51bf0e3
229
190
230
191
Existem muitas outras opções nas ferramentas do desenvolvedor além das já cobertas ao longo desta leitura. O manual completo está em <https://developers.google.com/web/tools/chrome-devtools>.
Copy file name to clipboardExpand all lines: 1-js/03-code-quality/05-testing-mocha/article.md
-54Lines changed: 0 additions & 54 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -50,60 +50,17 @@ describe("pow", function() {
50
50
51
51
Uma *spec* tem três principais blocos construtores, como pode ver acima:
52
52
53
-
<<<<<<< HEAD
54
53
`describe("título", function() { ... })`
55
54
: Que funcionalidade estamos a descrever. No nosso caso, estamos a descrever a função `pow`. São usados para agrupar "executores" ("*workers*") -- os blocos `it`.
56
-
=======
57
-
`describe("title", function() { ... })`
58
-
: What functionality we're describing? In our case we're describing the function `pow`. Used to group "workers" -- the `it` blocks.
59
-
>>>>>>> d78b01e9833009fab534462e05c03cffc51bf0e3
60
55
61
56
`it("descrição do caso exemplo", function() { ... })`
62
57
: No título de `it` nós, *de uma forma claramente legível*, descrevemos o caso exemplo em questão, e no segundo argumento está uma função que o testa.
63
58
64
59
`assert.equal(valor1, valor2)`
65
60
: O código dentro do bloco `it`, se a implementação estiver correta, não deverá mostrar erros.
66
61
67
-
<<<<<<< HEAD
68
62
```text
69
63
Funções `assert.*` são usadas para verificar se `pow` funciona como esperado. Aqui mesmo, estamos a usar uma delas -- `assert.equal`, que compara argumentos e dá como resultado um erro se eles não forem iguais. Aqui, ela verifica se o resultado de `pow(2, 3)` é `8`. Existem outros tipos de comparações e verificações, que adicionaremos mais adiante.
70
-
=======
71
-
Functions `assert.*` are used to check whether `pow` works as expected. Right here we're using one of them -- `assert.equal`, it compares arguments and yields an error if they are not equal. Here it checks that the result of `pow(2, 3)` equals `8`. There are other types of comparisons and checks, that we'll add later.
72
-
73
-
The specification can be executed, and it will run the test specified in `it` block. We'll see that later.
74
-
75
-
## The development flow
76
-
77
-
The flow of development usually looks like this:
78
-
79
-
1. An initial spec is written, with tests for the most basic functionality.
80
-
2. An initial implementation is created.
81
-
3. To check whether it works, we run the testing framework [Mocha](https://mochajs.org/) (more details soon) that runs the spec. While the functionality is not complete, errors are displayed. We make corrections until everything works.
82
-
4. Now we have a working initial implementation with tests.
83
-
5. We add more use cases to the spec, probably not yet supported by the implementations. Tests start to fail.
84
-
6. Go to 3, update the implementation till tests give no errors.
85
-
7. Repeat steps 3-6 till the functionality is ready.
86
-
87
-
So, the development is *iterative*. We write the spec, implement it, make sure tests pass, then write more tests, make sure they work etc. At the end we have both a working implementation and tests for it.
88
-
89
-
Let's see this development flow in our practical case.
90
-
91
-
The first step is already complete: we have an initial spec for `pow`. Now, before making the implementation, let's use a few JavaScript libraries to run the tests, just to see that they are working (they will all fail).
92
-
93
-
## The spec in action
94
-
95
-
Here in the tutorial we'll be using the following JavaScript libraries for tests:
96
-
97
-
- [Mocha](https://mochajs.org/) -- the core framework: it provides common testing functions including `describe` and `it` and the main function that runs tests.
98
-
- [Chai](https://www.chaijs.com/) -- the library with many assertions. It allows to use a lot of different assertions, for now we need only `assert.equal`.
99
-
- [Sinon](https://sinonjs.org/) -- a library to spy over functions, emulate built-in functions and more, we'll need it much later.
100
-
101
-
These libraries are suitable for both in-browser and server-side testing. Here we'll consider the browser variant.
102
-
103
-
The full HTML page with these frameworks and `pow` spec:
104
-
105
-
```html src="index.html"
106
-
>>>>>>> d78b01e9833009fab534462e05c03cffc51bf0e3
107
64
```
108
65
109
66
A especificação pode ser executada, e irá correr o teste especificado no bloco `it`. O que veremos mais adiante.
@@ -385,7 +342,6 @@ Os testes agora adicionados falham, porque a nossa implementação não possui s
385
342
386
343
```smart header="Outras asserções"
387
344
388
-
<<<<<<< HEAD
389
345
Por favor, observe a asserção `assert.isNaN`: ela verifica por `NaN`.
390
346
391
347
Existem ainda outras asserções em [Chai](http://chaijs.com), como por exemplo:
@@ -396,16 +352,6 @@ Existem ainda outras asserções em [Chai](http://chaijs.com), como por exemplo:
396
352
- `assert.isTrue(valor)` -- verifica se `valor ===true`
397
353
- `assert.isFalse(valor)` -- verifica se `valor ===false`
398
354
- ...a lista completa está em [docs](http://chaijs.com/api/assert/)
399
-
=======
400
-
There are other assertions in [Chai](https://www.chaijs.com/) as well, for instance:
401
-
402
-
- `assert.equal(value1, value2)` -- checks the equality `value1 == value2`.
Copy file name to clipboardExpand all lines: 1-js/03-code-quality/06-polyfills/article.md
+1-37Lines changed: 1 addition & 37 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,23 +1,13 @@
1
1
2
2
# Polyfills e transpilers
3
3
4
-
<<<<<<< HEAD
5
4
A linguagem JavaScript evolui constantemente. Novas propostas para a linguagem aparecem regularmente, elas são analisadas e, se consideradas válidas, são anexadas à lista em <https://tc39.github.io/ecma262/> e depois progridem para a [especificação (en)](https://www.ecma-international.org/publications-and-standards/standards/ecma-262/).
6
-
=======
7
-
The JavaScript language steadily evolves. New proposals to the language appear regularly, they are analyzed and, if considered worthy, are appended to the list at <https://tc39.github.io/ecma262/> and then progress to the [specification](https://www.ecma-international.org/publications-and-standards/standards/ecma-262/).
8
-
>>>>>>> d78b01e9833009fab534462e05c03cffc51bf0e3
9
5
10
6
Grupos por detrás dos interpretadores de JavaScript têm as suas próprias ideias sobre o que implementar primeiro. Eles podem decidir implementar propostas que estão em esboço e adiar coisas que já estão na spec, por serem menos interessantes ou apenas mais difíceis de fazer.
11
7
12
-
<<<<<<< HEAD
13
8
Assim, é muito comum que um interpretador implemente apenas parte de um padrão.
14
9
15
10
Uma boa página para se ver o estágio atual de suporte de funcionalidades da linguagem é <https://compat-table.github.io/compat-table/es6/> (é extensa, nós ainda temos muito que estudar).
16
-
=======
17
-
So it's quite common for an engine to implement only part of the standard.
18
-
19
-
A good page to see the current state of support for language features is <https://compat-table.github.io/compat-table/es6/> (it's big, we have a lot to study yet).
20
-
>>>>>>> d78b01e9833009fab534462e05c03cffc51bf0e3
21
11
22
12
Como programadores, nós gostaríamos de usar as funcionalidades mais recentes. Quantas mais forem as coisas boas - melhor!
23
13
@@ -50,15 +40,9 @@ Agora, o código reescrito está adequado a interpretadores de JavaScript antigo
50
40
51
41
Geralmente, um desenvolvedor executa o transpiler na sua própria máquina, e depois coloca o código transpilado no servidor.
52
42
53
-
<<<<<<< HEAD
54
43
Falando em nomes, o [Babel](https://babeljs.io) é um dos mais prominentes transpilers por aí.
55
44
56
45
Sistemas para a construção de projetos modernos, tais como o [webpack](https://webpack.js.org/), fornecem meios para automaticamente correr o transpiler em cada alteração do código, e assim é muito fácil o integrar no processo de desenvolvimento.
57
-
=======
58
-
Speaking of names, [Babel](https://babeljs.io) is one of the most prominent transpilers out there.
59
-
60
-
Modern project build systems, such as [webpack](https://webpack.js.org/), provide a means to run a transpiler automatically on every code change, so it's very easy to integrate into the development process.
61
-
>>>>>>> d78b01e9833009fab534462e05c03cffc51bf0e3
62
46
63
47
## Polyfills
64
48
@@ -85,40 +69,20 @@ if (!Math.trunc) { // se a função não existir
85
69
}
86
70
```
87
71
88
-
<<<<<<< HEAD
89
72
O JavaScript é uma linguagem altamente dinâmica. Scripts podem adicionar/modificar quaisquer funções, incluindo até incorporadas.
90
73
91
-
Duas interessantes bibliotecas de polyfills são:
92
-
- [core js](https://github.com/zloirock/core-js) que suporta muitas funcionalidades, e permite apenas incluir aquelas necessárias.
93
-
- [polyfill.io](http://polyfill.io) um serviço que fornece um script com polyfills, dependendo das funcionalidades e do navegador do utilizador.
74
+
Uma biblioteca interessante de polyfill é [core js](https://github.com/zloirock/core-js) que suporta muitas funcionalidades, e permite apenas incluir aquelas necessárias.
94
75
95
76
## Resumo
96
-
=======
97
-
JavaScript is a highly dynamic language. Scripts may add/modify any function, even built-in ones.
98
-
99
-
One interesting polyfill library is [core-js](https://github.com/zloirock/core-js), which supports a wide range of features and allows you to include only the ones you need.
100
-
>>>>>>> d78b01e9833009fab534462e05c03cffc51bf0e3
101
77
102
78
Neste capítulo, gostaríamos de o motivar a estudar funcionalidades modernas ou até em esboço da linguagem, mesmo que elas ainda não tenham um bom suporte pelos interpretadores de JavaScript.
103
79
104
80
Apenas não se esqueça de usar um transpiler (se empregar sintaxe ou operadores modernos) e polyfills (para adicionar funções que possam estar ausentes). E eles irão garantir que o código funcione.
105
81
106
-
<<<<<<< HEAD
107
82
Por exemplo, mais adiante quando estiver familiarizado com o JavaScript, você pode configurar um sistema para a construção de código com base no [webpack](https://webpack.js.org/) e com o plugin [babel-loader](https://github.com/babel/babel-loader).
108
83
109
84
Bons recursos que mostram o estágio atual do suporte para várias funcionalidades:
110
85
- <https://compat-table.github.io/compat-table/es6/> - para puro JavaScript.
111
86
- <https://caniuse.com/> - para funções com relação ao navegador.
112
-
=======
113
-
Just don't forget to use a transpiler (if using modern syntax or operators) and polyfills (to add functions that may be missing). They'll ensure that the code works.
114
-
115
-
For example, later when you're familiar with JavaScript, you can setup a code build system based on [webpack](https://webpack.js.org/) with the [babel-loader](https://github.com/babel/babel-loader) plugin.
116
-
117
-
Good resources that show the current state of support for various features:
118
-
- <https://compat-table.github.io/compat-table/es6/> - for pure JavaScript.
119
-
- <https://caniuse.com/> - for browser-related functions.
120
-
121
-
P.S. Google Chrome is usually the most up-to-date with language features, try it if a tutorial demo fails. Most tutorial demos work with any modern browser though.
122
-
>>>>>>> d78b01e9833009fab534462e05c03cffc51bf0e3
123
87
124
88
P.S. O Google Chrome, geralmente é o mais atualizado relativamente a funcionalidades da linguagem, experimente-o se um exemplo no tutorial falhar. Contudo, a maioria dos exemplos no tutorial funcionam com qualquer navegador moderno.
0 commit comments