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
Sponsored
·
Your Podcast. Everywhere. Effortlessly.
Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.
→
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
68
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
220
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
AI時代のキャリアプラン「技術の引力」からの脱出と「問い」へのいざない / tech-gravity
minodriven
16
5.4k
Fragmented Architectures
denyspoltorak
0
140
Automatic Grammar Agreementと Markdown Extended Attributes について
kishikawakatsumi
0
180
AIフル活用時代だからこそ学んでおきたい働き方の心得
shinoyu
0
120
AIで開発はどれくらい加速したのか?AIエージェントによるコード生成を、現場の評価と研究開発の評価の両面からdeep diveしてみる
daisuketakeda
1
950
Fluid Templating in TYPO3 14
s2b
0
120
Vibe codingでおすすめの言語と開発手法
uyuki234
0
210
カスタマーサクセス業務を変革したヘルススコアの実現と学び
_hummer0724
0
490
The Past, Present, and Future of Enterprise Java
ivargrimstad
0
420
コントリビューターによるDenoのすゝめ / Deno Recommendations by a Contributor
petamoriken
0
200
Spinner 軸ズレ現象を調べたらレンダリング深淵に飲まれた #レバテックMeetup
bengo4com
1
220
KIKI_MBSD Cybersecurity Challenges 2025
ikema
0
1.3k
Featured
See All Featured
Building Experiences: Design Systems, User Experience, and Full Site Editing
marktimemedia
0
400
Discover your Explorer Soul
emna__ayadi
2
1.1k
"I'm Feeling Lucky" - Building Great Search Experiences for Today's Users (#IAC19)
danielanewman
231
22k
Exploring anti-patterns in Rails
aemeredith
2
240
Building Better People: How to give real-time feedback that sticks.
wjessup
370
20k
Being A Developer After 40
akosma
91
590k
Pawsitive SEO: Lessons from My Dog (and Many Mistakes) on Thriving as a Consultant in the Age of AI
davidcarrasco
0
60
What does AI have to do with Human Rights?
axbom
PRO
0
2k
Speed Design
sergeychernyshev
33
1.5k
Mind Mapping
helmedeiros
PRO
0
71
Visual Storytelling: How to be a Superhuman Communicator
reverentgeek
2
420
Fireside Chat
paigeccino
41
3.8k
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