Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
Testes em JavaScript: A Maneira Correta
Search
Sponsored
·
Ship Features Fearlessly
Turn features on and off without deploys. Used by thousands of Ruby developers.
→
Lucas Fernandes da Costa
May 05, 2017
Programming
93
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
Testes em JavaScript: A Maneira Correta
Talk apresentada no TDC Florianópolis 2017.
Lucas Fernandes da Costa
May 05, 2017
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
94
What did we Learn with JavaScript Fatigue? (FrontMania)
lucasfcosta
1
90
How I'm still not using GUIs in 2019
lucasfcosta
0
83
Programming with Birds - There is a Bluebird in My Talk That Wants to Get Out (LambdAle 2018)
lucasfcosta
0
150
What can we learn with JavaScript Fatigue? - FrontEnd United
lucasfcosta
2
260
What Can We Learn With JavaScript Fatigue? - The Conf SP
lucasfcosta
0
110
What Can We Learn With JavaScript Fatigue? - NebraskaJS
lucasfcosta
2
140
JavaScript Behind the Scenes: Meta Programming (FluentConf 2017)
lucasfcosta
0
160
JavaScript Behind the Scenes: Meta Programming
lucasfcosta
0
280
Other Decks in Programming
See All in Programming
LLM 101
dalinaum
0
360
Modernizing iOS Apps
seyfoyun
0
140
社内AIエージェント「Askワンバン」における コストチューニングの取り組み
t0yohei
0
120
Materialが消えた日 〜真っ白なFlutterキャンバスにRenderObjectで絵を描く〜
umigishiaoi
0
120
3回つくってわかった、 定期実行ジョブ基盤の本質情報
takai
4
3.5k
クラウドエージェントは、 何がそんなに便利なのか / what makes cloud agents so useful
rkaga
3
630
golang-bob.pdf
iwatsukayura
0
150
Optunaを作ったときにやりたかったこと、その後 (2026/10/16, Optuna Meetup #3)
iwiwi
4
1.4k
Kotlinの15年とServer-Side Kotlin
n_takehata
1
170
コードで差別化できない時代の ソフトウェアエンジニアリング / Software Engineering in an Era Where Code Doesn’t Differentiate
kishida
2
220
flutter_test のその先へ — Flutter アプリの LLM 機能に「評価」という品質保証を
kosukesaigusa
0
140
月間100万人のサービス刷新で、 技術選定をHonoに振り切った話
yutobara
8
7.1k
Featured
See All Featured
From Legacy to Launchpad: Building Startup-Ready Communities
dugsong
0
360
職位にかかわらず全員がリーダーシップを発揮するチーム作り / Building a team where everyone can demonstrate leadership regardless of position
madoxten
70
68k
A Soul's Torment
seathinner
8
3.9k
Efficient Content Optimization with Google Search Console & Apps Script
katarinadahlin
PRO
1
950
Un-Boring Meetings
codingconduct
0
470
For a Future-Friendly Web
brad_frost
184
11k
Visual Storytelling: How to be a Superhuman Communicator
reverentgeek
2
730
Lessons Learnt from Crawling 1000+ Websites
charlesmeaden
PRO
1
1.7k
Improving Core Web Vitals using Speculation Rules API
sergeychernyshev
21
1.7k
The Pragmatic Product Professional
lauravandoore
37
7.5k
No one is an island. Learnings from fostering a developers community.
thoeni
21
3.9k
AI Search: Implications for SEO and How to Move Forward - #ShenzhenSEOConference
aleyda
1
1.4k
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