Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Testes em JavaScript: A Maneira Correta
Search
Lucas Fernandes da Costa
May 05, 2017
Programming
0
78
Testes em JavaScript: A Maneira Correta
Talk apresentada no TDC Florianópolis 2017.
Lucas Fernandes da Costa
May 05, 2017
Tweet
Share
More Decks by Lucas Fernandes da Costa
See All by Lucas Fernandes da Costa
Types, tests, and why flat-earthers are bad at QA (HolyJS)
lucasfcosta
0
64
What did we Learn with JavaScript Fatigue? (FrontMania)
lucasfcosta
1
77
How I'm still not using GUIs in 2019
lucasfcosta
0
69
Programming with Birds - There is a Bluebird in My Talk That Wants to Get Out (LambdAle 2018)
lucasfcosta
0
130
What can we learn with JavaScript Fatigue? - FrontEnd United
lucasfcosta
2
230
What Can We Learn With JavaScript Fatigue? - The Conf SP
lucasfcosta
0
100
What Can We Learn With JavaScript Fatigue? - NebraskaJS
lucasfcosta
2
120
JavaScript Behind the Scenes: Meta Programming (FluentConf 2017)
lucasfcosta
0
150
JavaScript Behind the Scenes: Meta Programming
lucasfcosta
0
260
Other Decks in Programming
See All in Programming
なぜSQLはAIぽく見えるのか/why does SQL look AI like
florets1
0
470
SourceGeneratorのススメ
htkym
0
200
OSSとなったswift-buildで Xcodeのビルドを差し替えられるため 自分でXcodeを直せる時代になっている ダイアモンド問題編
yimajo
3
620
Raku Raku Notion 20260128
hareyakayuruyaka
0
340
疑似コードによるプロンプト記述、どのくらい正確に実行される?
kokuyouwind
0
390
CSC307 Lecture 04
javiergs
PRO
0
660
【卒業研究】会話ログ分析によるユーザーごとの関心に応じた話題提案手法
momok47
0
200
AI時代の認知負荷との向き合い方
optfit
0
160
副作用をどこに置くか問題:オブジェクト指向で整理する設計判断ツリー
koxya
1
610
Lambda のコードストレージ容量に気をつけましょう
tattwan718
0
140
React 19でつくる「気持ちいいUI」- 楽観的UIのすすめ
himorishige
11
7.4k
Rust 製のコードエディタ “Zed” を使ってみた
nearme_tech
PRO
0
200
Featured
See All Featured
I Don’t Have Time: Getting Over the Fear to Launch Your Podcast
jcasabona
34
2.6k
Data-driven link building: lessons from a $708K investment (BrightonSEO talk)
szymonslowik
1
910
What’s in a name? Adding method to the madness
productmarketing
PRO
24
3.9k
Faster Mobile Websites
deanohume
310
31k
GraphQLの誤解/rethinking-graphql
sonatard
74
11k
Reflections from 52 weeks, 52 projects
jeffersonlam
356
21k
Context Engineering - Making Every Token Count
addyosmani
9
660
The Art of Delivering Value - GDevCon NA Keynote
reverentgeek
16
1.8k
Believing is Seeing
oripsolob
1
56
How People are Using Generative and Agentic AI to Supercharge Their Products, Projects, Services and Value Streams Today
helenjbeal
1
130
Improving Core Web Vitals using Speculation Rules API
sergeychernyshev
21
1.4k
Connecting the Dots Between Site Speed, User Experience & Your Business [WebExpo 2025]
tammyeverts
11
830
Transcript
None
a maneira correta github lucasfcosta twitter lfernandescosta
Testes em Javascript A M A N E I R
A C O R R E T A lucasfcosta lfernandescosta
lucasfcosta lfernandescosta quem sou eu?
"Automated crap is still crap" Why most unit testing is
waste - James O. Coplien
the testing mindset
Martin Fowler Testes unitários não são tudo
Você não pode provar que seu código funciona
Você não pode provar que seu código funciona Você só
pode provar que ele não funciona
Você não pode testar todos os inputs possíveis
Testes que nunca falham não produzem informação
Testes que nunca falham não produzem informação Testes de baixo
risco possuem baixo valor
Green Bar Fever
Green Bar Fever
testes como especificações Testes ajudam a esclarecer especificações Testes servem
como especificação Ajudam a entender a codebase
determinismo
determinismo
determinismo Input Output Unit Under Test
reproducible builds Input Unit Under Test initial state
reproducible builds Input Output Unit Under Test initial state
reproducible builds Input Output Unit Under Test final state
reproducible builds Input Output Unit Under Test final state entre
testes: cleanup
reproducible builds Input Output Unit Under Test initial state entre
testes: cleanup
Testes não deterministas são inúteis Impossível diferenciar bugs de não-determinismo
Program to an interface not an implementation menos acoplamento
“TDD REDUCES FEAR” Kent Beck
Confiança Tamanho dos passos
teste seu código filesystem calls databases crypto libraries de terceiros
teste seu código filesystem calls databases crypto libraries de terceiros
responsabilidade de quem mantém essas ferramentas testes de integração/black box garantem o funcionamento delas
na prática
Ferramentas test runners assertion libraries code coverage mocks, stubs, spies
multi- platform o pipeline de testes
test runners
tape test runners !== assertions
4 elementos para bons test suites
isolamento um teste unitário testa apenas uma unidade (função)
isolamento + precisão para detectar erros
isolamento BDD GivenWhenThen
isolamento
foco o mínimo de verificações por teste
foco um teste = um objetivo
desacoplamento Unit Under Test Provê uma entrada Espera uma saída
X Y Não importa como é feito
desacoplamento Você paga por testes em manutenção
independência function a(input) { return b(input, c(input)) }
independência teste de “a” falha function a(input) { return b(input,
c(input)) }
independência teste de “a” falha o erro está em a,
b, ou c? function a(input) { return b(input, c(input)) }
independência prover resultados corretos de “b” e “c”
independência
4 elementos para bons test suites ISOLAMENTO FOCO DESACOPLAMENTO INDEPENDÊNCIA
ISOLAMENTO FOCO DESACOPLAMENTO INDEPENDÊNCIA 4 elementos para bons test suites
ISOLAMENTO FOCO DESACOPLAMENTO INDEPENDÊNCIA 4 elementos para bons test suites
ISOLAMENTO FOCO DESACOPLAMENTO INDEPENDÊNCIA 4 elementos para bons test suites
assertions
Verificações expect(result).to.be.equal(10) assert.true(isBlue) assert.equals(result, 10)
assertions should.js must.js
erros comuns ao fazer verificações
expect(result).to.not.be.equal(10) expect(arr).to.not.contain(1, 2, 3) negações
+ ∞ - ∞ 0 Resultados de f(x) negações
+ ∞ - ∞ 0 Resultados de f(x) expect(result).to.not.be.equal(1) negações
+ ∞ - ∞ 0 1 expect(result).to.not.be.equal(1) negações
negações + ∞ - ∞ 0 1 expect(result).to.not.be.equal(1) Total de
saídas que passam = ∞ - 1
asserções frouxas expect(result).to.be.a.number
asserções frouxas Desde 5e-324 até 1.7976931348623157e+308 expect(result).to.be.a.number
expect(result).to.be.a.number expect(arr).to.contain(1) asserções frouxas
múltiplos outputs
function mult(a, b) { let result = 0 for (let
i = 0; i < b; i++) { result = sum(result + a) } return result } detalhes de implementação
mult(3, 2) expect(sum).to.be.calledTwice function mult(a, b) { return a *
b; } refactor quebra detalhes de implementação
asserções circulares catFactory -> Cria objetos gato createBlueCat -> Cria
um gato azul (chama catFactory)
asserções circulares expect(createBlueCat()) .to.be .equal(catFactory.create(‘blue’))
asserções circulares expect(createBlueCat()) .to.be .equal(catFactory.create(‘blue’)) teste tautológico
asserções circulares implementação vs. implementação
erros comuns ao fazer verificações ASSERÇÕES FROUXAS MÚLTIPLOS OUTPUTS DETALHES
DE IMPLEMENTAÇÃO ASSERÇÕES CIRCULARES NEGAÇÕES
erros comuns ao fazer verificações ASSERÇÕES FROUXAS MÚLTIPLOS OUTPUTS DETALHES
DE IMPLEMENTAÇÃO ASSERÇÕES CIRCULARES NEGAÇÕES
erros comuns ao fazer verificações ASSERÇÕES FROUXAS MÚLTIPLOS OUTPUTS DETALHES
DE IMPLEMENTAÇÃO ASSERÇÕES CIRCULARES NEGAÇÕES
erros comuns ao fazer verificações ASSERÇÕES FROUXAS MÚLTIPLOS OUTPUTS DETALHES
DE IMPLEMENTAÇÃO ASSERÇÕES CIRCULARES NEGAÇÕES
erros comuns ao fazer verificações ASSERÇÕES FROUXAS MÚLTIPLOS OUTPUTS DETALHES
DE IMPLEMENTAÇÃO ASSERÇÕES CIRCULARES NEGAÇÕES
mocks, stubs, spies
spies guardam dados sobre a utilização de funções • quantas
vezes foi chamada • com quais argumentos foi chamada • qual era o valor de this podemos fazer verificações sobre esses dados
stubs guardam dados sobre a utilização de funções sobrescrevem comportamentos
+
stubs Eliminam não-determinismo
stubs Eliminam não-determinismo Eliminam side-effects
stubs Ajudam à fazer isolamento Eliminam não-determinismo Eliminam side-effects
stubs Ajudam à fazer isolamento Eliminam não-determinismo Eliminam side-effects
mocks expectativas pré-programadas stubs + verificações
sinon.js
utilizando mocks, stubs & spies com sabedoria
utilizando mocks, stubs & spies com sabedoria Voltaire, 1793 une
grande responsabilité est la suite inséparable d’un grand pouvoir.
utilizando mocks, stubs & spies com sabedoria TIO BEN RIP
stubs, spies ou mocks? spies stubs mocks quando quero manter
o comportamento e checar chamadas quando quero substituir comportamentos e checar chamadas quando quero dizer como uma determinada peça deve ser usada (conjunto de regras)
sandboxes facilitam setup e teardown facilitam eliminar dependências entre testes
mais facilidade de resetar dados
fake timers implementação síncrona de relógio + determinismo (datas) testes
mais rápidos (não dependem de tempo)
STUBS, SPIES OU MOCKS? utilizando mocks, stubs & spies com
sabedoria
DETERMINISMO E SIDE-EFFECTS STUBS, SPIES OU MOCKS? utilizando mocks, stubs
& spies com sabedoria
SANDBOXES DETERMINISMO E SIDE-EFFECTS STUBS, SPIES OU MOCKS? utilizando mocks,
stubs & spies com sabedoria
SANDBOXES DETERMINISMO E SIDE-EFFECTS STUBS, SPIES OU MOCKS? FAKE TIMERS
utilizando mocks, stubs & spies com sabedoria
multiple platforms
diferentes features diferentes implementações
None
setup
setup web server
setup web server inicia browser
setup web server inicia browser browser conecta
testes headless • velocidade • acesso às APIs do browser
• múltiplos environments (CI)
testes headless phantomjs
packaging
code coverage
code coverage é uma medida interessante, porém imprecisa
é impossível testar todos os inputs existentes
testes sem verificações não significam nada
medindo code coverage
testes geração de relatórios .lcov medindo code coverage instrumentação
o pipeline de testes
continuous integration
git hooks
o pipeline de testes TASK RUNNER NPM (recomendado) Gulp Grunt
INSTRUMENTAÇÃO Istanbul TESTING Mocha Chai Tape Jest Jasmine
BROWSER TESTING Karma COVERAGE REPORTS Istanbul PACKAGING Browserify Webpack
Coveralls COMBINAÇÃO DE RELATÓRIOS lcov-result-merger COVERAGE TRACKING
Ferramentas test runners assertion libraries code coverage mocks, stubs, spies
multi- platform o pipeline de testes
Ferramentas test runners assertion libraries code coverage mocks, stubs, spies
multi- platform o pipeline de testes
Ferramentas test runners assertion libraries code coverage mocks, stubs, spies
multi- platform o pipeline de testes
Ferramentas test runners assertion libraries code coverage mocks, stubs, spies
multi- platform o pipeline de testes
Ferramentas test runners assertion libraries code coverage mocks, stubs, spies
multi- platform o pipeline de testes
Ferramentas test runners assertion libraries code coverage mocks, stubs, spies
multi- platform o pipeline de testes
obrigado! lucasfcosta lfernandescosta lucasfcosta.com