SlideShare a Scribd company logo
1 of 29
Download to read offline
Async tests giving you a sinking feeling?
<span id="numbers">{{ numbers | async }}</span>
<button (click)=“getNumbers()”>Subscribe</button>
The Component
getNumbers() {
Observable.interval(1000)
.subscribe(x => this.numbers.next(x));
}
The Test
it('should have a value', () => {
element.querySelector(‘button’).click();
expect(numbers.textContent).toContain(‘0');
});
😢
The Problem of change detection
<html>
AngularJS…
Change detection strategies
React…
Change detection strategies
Angular…
Change detection strategies
How Angular does change detection
addEventListener() / removeEventListener()
xhr request callback
setTimeout() / setInterval()
requestAnimationFrame()
prompt() / alert()
Sources of change
▸ Detect when async functions run
▸ Run a bit of extra code when they do
▸ Angular zone is called ngZone
ZoneJS
Running in the ngZone
setTimeout(callback, delay);Zone.setTimeout(callback, delay);
Zone.setTimeout = function (callback, delay) {
const wrapped = function () {
callback();
callAngularChangeDetection();
};
setTimeout(wrapped, delay);
}
Tragically, test code doesn’t run in the ngZone
No zone for you!
😢
it('should show the success message', (done) => {
component.submit()
We don’t need no automatic change detection
SUBMIT SUCCESS!
.then(() => {
expect(getElement(‘.success’)).toBeTruthy();
done();
});
});
.then(() => fixture.detectChanges())
getNumbers() {
Observable.interval(1000)
.subscribe(x => this.numbers.next(x));
}
Who watches the watchers?
it('should have a value', () => {
element.querySelector(‘button’).click();
fixture.detectChanges();
expect(numbers.textContent).toContain('1');
});
🤔
- Special zone for running tests
- Super powers!
▸ tick()
▸ flush()/flushMicrotasks()
fakeAsync to the rescue
tick(n): advance time n milliseconds
Tick tock
it(‘should have a value’, fakeAsync(() => {
element.querySelector(‘button’).click();
tick(1000);
fixture.detectChanges();
expect(element.textContent).toContain('0');
}));
So close…
Error: 1 periodic timer(s) still in the queue.
Description
If there are any pending timers at the end of the function, an
exception will be thrown.
Remain calm
it(‘should have a value’, fakeAsync(() => {
component.getNumbers();
tick(1000);
fixture.detectChanges();
expect(element.textContent).toContain(‘0');
}));
discardPeriodicTasks();
Chrome 66.0.3359 (Mac OS X 10.12.6): Executed 1 of 1 SUCCESS (0.135 secs / 0.127 secs)
▸ flushMicrotasks()
‣ execute all remaining micro tasks
▸ flush()
▸ execute all remaining tasks
▸ fixture.whenStable()
▸ flush(), but different
What if I’m not testing an interval?
it('should set the flag', () => {
let flag = false;
Promise.resolve()
.then(() => flag = true);
expect(flag).toBe(true);
});
flushMicrotasks()
Expected false to be true.
it('should set the flag', (done) => {
let flag = false;
Promise.resolve()
.then(() => flag = true)
.then(() => {
expect(flag).toBe(true);
done();
});
});
The old-fashioned way
it('should set the flag', fakeAsync(() => {
let flag = false;
Promise.resolve()
.then(() => flag = true);
expect(flag).toBe(true);
}));
The Angular way
flushMicrotasks();
it('should set the flag', fakeAsync(() => {
const time = Math.random() * 10000;
let flag = false;
setTimeout(() => flag = true, time);
expect(flag).toBe(false);
const timeElapsed = flush();
expect(flag).toBe(true);
expect(timeElapsed).toBe(time);
}));
flush()
fixture.whenStable(): a different way to flush
it('should be true', fakeAsync(() => {
fixture.whenStable()
.then(() => expect(app.result).toBe(true));
}));
ngOnInit() {
someAsyncThing().then(() => this.result = true);
}
it('should be true', fakeAsync(() => {
fixture.whenRenderingDone()
.then(() => {
expect(app.result).toBe(true);
});
}));
And one last thing…
▸ fixture.detectChanges()
▸ fakeAsync() zone
▸ tick(), flush() & flushMicrotasks()
▸ fixture.whenStable() & fixture.whenRenderingDone()
Our weapons in the fight against async tests
@ErinJZimmer

More Related Content

What's hot

VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEDarwin Durand
 
The Ring programming language version 1.5.1 book - Part 62 of 180
The Ring programming language version 1.5.1 book - Part 62 of 180The Ring programming language version 1.5.1 book - Part 62 of 180
The Ring programming language version 1.5.1 book - Part 62 of 180Mahmoud Samir Fayed
 
The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184Mahmoud Samir Fayed
 
如何「畫圖」寫測試 - RxJS Marble Test
如何「畫圖」寫測試 - RxJS Marble Test如何「畫圖」寫測試 - RxJS Marble Test
如何「畫圖」寫測試 - RxJS Marble Test名辰 洪
 
The Ring programming language version 1.6 book - Part 64 of 189
The Ring programming language version 1.6 book - Part 64 of 189The Ring programming language version 1.6 book - Part 64 of 189
The Ring programming language version 1.6 book - Part 64 of 189Mahmoud Samir Fayed
 
Redux saga: managing your side effects. Also: generators in es6
Redux saga: managing your side effects. Also: generators in es6Redux saga: managing your side effects. Also: generators in es6
Redux saga: managing your side effects. Also: generators in es6Ignacio Martín
 
Orsiso
OrsisoOrsiso
Orsisoe27
 
The evolution of redux action creators
The evolution of redux action creatorsThe evolution of redux action creators
The evolution of redux action creatorsGeorge Bukhanov
 
Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012Sandeep Joshi
 
The Ring programming language version 1.6 book - Part 71 of 189
The Ring programming language version 1.6 book - Part 71 of 189The Ring programming language version 1.6 book - Part 71 of 189
The Ring programming language version 1.6 book - Part 71 of 189Mahmoud Samir Fayed
 
The Ring programming language version 1.5.4 book - Part 69 of 185
The Ring programming language version 1.5.4 book - Part 69 of 185The Ring programming language version 1.5.4 book - Part 69 of 185
The Ring programming language version 1.5.4 book - Part 69 of 185Mahmoud Samir Fayed
 
Calculator code with scientific functions in java
Calculator code with scientific functions in java Calculator code with scientific functions in java
Calculator code with scientific functions in java Amna Nawazish
 
Universal JavaScript
Universal JavaScriptUniversal JavaScript
Universal JavaScript名辰 洪
 
The Ring programming language version 1.10 book - Part 68 of 212
The Ring programming language version 1.10 book - Part 68 of 212The Ring programming language version 1.10 book - Part 68 of 212
The Ring programming language version 1.10 book - Part 68 of 212Mahmoud Samir Fayed
 
The Ring programming language version 1.7 book - Part 66 of 196
The Ring programming language version 1.7 book - Part 66 of 196The Ring programming language version 1.7 book - Part 66 of 196
The Ring programming language version 1.7 book - Part 66 of 196Mahmoud Samir Fayed
 
2019-10-05 - Untangled - Voxxed days ticino
2019-10-05 - Untangled - Voxxed days ticino2019-10-05 - Untangled - Voxxed days ticino
2019-10-05 - Untangled - Voxxed days ticinoArnaud Bos
 
The Ring programming language version 1.5.1 book - Part 37 of 180
The Ring programming language version 1.5.1 book - Part 37 of 180The Ring programming language version 1.5.1 book - Part 37 of 180
The Ring programming language version 1.5.1 book - Part 37 of 180Mahmoud Samir Fayed
 

What's hot (20)

VISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLEVISUALIZAR REGISTROS EN UN JTABLE
VISUALIZAR REGISTROS EN UN JTABLE
 
The Ring programming language version 1.5.1 book - Part 62 of 180
The Ring programming language version 1.5.1 book - Part 62 of 180The Ring programming language version 1.5.1 book - Part 62 of 180
The Ring programming language version 1.5.1 book - Part 62 of 180
 
The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184
 
如何「畫圖」寫測試 - RxJS Marble Test
如何「畫圖」寫測試 - RxJS Marble Test如何「畫圖」寫測試 - RxJS Marble Test
如何「畫圖」寫測試 - RxJS Marble Test
 
The Ring programming language version 1.6 book - Part 64 of 189
The Ring programming language version 1.6 book - Part 64 of 189The Ring programming language version 1.6 book - Part 64 of 189
The Ring programming language version 1.6 book - Part 64 of 189
 
Redux saga: managing your side effects. Also: generators in es6
Redux saga: managing your side effects. Also: generators in es6Redux saga: managing your side effects. Also: generators in es6
Redux saga: managing your side effects. Also: generators in es6
 
Orsiso
OrsisoOrsiso
Orsiso
 
The evolution of redux action creators
The evolution of redux action creatorsThe evolution of redux action creators
The evolution of redux action creators
 
Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012
 
Easy Button
Easy ButtonEasy Button
Easy Button
 
The Ring programming language version 1.6 book - Part 71 of 189
The Ring programming language version 1.6 book - Part 71 of 189The Ring programming language version 1.6 book - Part 71 of 189
The Ring programming language version 1.6 book - Part 71 of 189
 
Der perfekte 12c trigger
Der perfekte 12c triggerDer perfekte 12c trigger
Der perfekte 12c trigger
 
The Ring programming language version 1.5.4 book - Part 69 of 185
The Ring programming language version 1.5.4 book - Part 69 of 185The Ring programming language version 1.5.4 book - Part 69 of 185
The Ring programming language version 1.5.4 book - Part 69 of 185
 
Calculator code with scientific functions in java
Calculator code with scientific functions in java Calculator code with scientific functions in java
Calculator code with scientific functions in java
 
Universal JavaScript
Universal JavaScriptUniversal JavaScript
Universal JavaScript
 
The Ring programming language version 1.10 book - Part 68 of 212
The Ring programming language version 1.10 book - Part 68 of 212The Ring programming language version 1.10 book - Part 68 of 212
The Ring programming language version 1.10 book - Part 68 of 212
 
The Ring programming language version 1.7 book - Part 66 of 196
The Ring programming language version 1.7 book - Part 66 of 196The Ring programming language version 1.7 book - Part 66 of 196
The Ring programming language version 1.7 book - Part 66 of 196
 
2019-10-05 - Untangled - Voxxed days ticino
2019-10-05 - Untangled - Voxxed days ticino2019-10-05 - Untangled - Voxxed days ticino
2019-10-05 - Untangled - Voxxed days ticino
 
The Ring programming language version 1.5.1 book - Part 37 of 180
The Ring programming language version 1.5.1 book - Part 37 of 180The Ring programming language version 1.5.1 book - Part 37 of 180
The Ring programming language version 1.5.1 book - Part 37 of 180
 
Thread base theory test
Thread base theory testThread base theory test
Thread base theory test
 

Similar to Async Testing giving you a sinking feeling

Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the mastersAra Pehlivanian
 
Promise: async programming hero
Promise: async programming heroPromise: async programming hero
Promise: async programming heroThe Software House
 
Workshop 5: JavaScript testing
Workshop 5: JavaScript testingWorkshop 5: JavaScript testing
Workshop 5: JavaScript testingVisual Engineering
 
New feature of async fakeAsync test in angular
New feature of async fakeAsync test in angularNew feature of async fakeAsync test in angular
New feature of async fakeAsync test in angularJia Li
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSAdam L Barrett
 
To Err Is Human
To Err Is HumanTo Err Is Human
To Err Is HumanAlex Liu
 
생산적인 개발을 위한 지속적인 테스트
생산적인 개발을 위한 지속적인 테스트생산적인 개발을 위한 지속적인 테스트
생산적인 개발을 위한 지속적인 테스트기룡 남
 
Google App Engine Developer - Day3
Google App Engine Developer - Day3Google App Engine Developer - Day3
Google App Engine Developer - Day3Simon Su
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptjnewmanux
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsPiotr Pelczar
 
A promise is a Promise
A promise is a PromiseA promise is a Promise
A promise is a PromiseMateusz Bryła
 
Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and httpAlexe Bogdan
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesAnkit Rastogi
 
ES6, 잘 쓰고 계시죠?
ES6, 잘 쓰고 계시죠?ES6, 잘 쓰고 계시죠?
ES6, 잘 쓰고 계시죠?장현 한
 
You will learn RxJS in 2017
You will learn RxJS in 2017You will learn RxJS in 2017
You will learn RxJS in 2017名辰 洪
 

Similar to Async Testing giving you a sinking feeling (20)

Rxjs ngvikings
Rxjs ngvikingsRxjs ngvikings
Rxjs ngvikings
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
 
Promise: async programming hero
Promise: async programming heroPromise: async programming hero
Promise: async programming hero
 
Angular2 rxjs
Angular2 rxjsAngular2 rxjs
Angular2 rxjs
 
Workshop 5: JavaScript testing
Workshop 5: JavaScript testingWorkshop 5: JavaScript testing
Workshop 5: JavaScript testing
 
New feature of async fakeAsync test in angular
New feature of async fakeAsync test in angularNew feature of async fakeAsync test in angular
New feature of async fakeAsync test in angular
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 
To Err Is Human
To Err Is HumanTo Err Is Human
To Err Is Human
 
생산적인 개발을 위한 지속적인 테스트
생산적인 개발을 위한 지속적인 테스트생산적인 개발을 위한 지속적인 테스트
생산적인 개발을 위한 지속적인 테스트
 
Rxjs marble-testing
Rxjs marble-testingRxjs marble-testing
Rxjs marble-testing
 
Rxjs swetugg
Rxjs swetuggRxjs swetugg
Rxjs swetugg
 
Google App Engine Developer - Day3
Google App Engine Developer - Day3Google App Engine Developer - Day3
Google App Engine Developer - Day3
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
 
Mockito intro
Mockito introMockito intro
Mockito intro
 
A promise is a Promise
A promise is a PromiseA promise is a Promise
A promise is a Promise
 
Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and http
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
 
ES6, 잘 쓰고 계시죠?
ES6, 잘 쓰고 계시죠?ES6, 잘 쓰고 계시죠?
ES6, 잘 쓰고 계시죠?
 
You will learn RxJS in 2017
You will learn RxJS in 2017You will learn RxJS in 2017
You will learn RxJS in 2017
 

Recently uploaded

WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...WSO2
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
WSO2CON2024 - Why Should You Consider Ballerina for Your Next Integration
WSO2CON2024 - Why Should You Consider Ballerina for Your Next IntegrationWSO2CON2024 - Why Should You Consider Ballerina for Your Next Integration
WSO2CON2024 - Why Should You Consider Ballerina for Your Next IntegrationWSO2
 
WSO2CON 2024 - Building a Digital Government in Uganda
WSO2CON 2024 - Building a Digital Government in UgandaWSO2CON 2024 - Building a Digital Government in Uganda
WSO2CON 2024 - Building a Digital Government in UgandaWSO2
 
WSO2Con2024 - Facilitating Broadband Switching Services for UK Telecoms Provi...
WSO2Con2024 - Facilitating Broadband Switching Services for UK Telecoms Provi...WSO2Con2024 - Facilitating Broadband Switching Services for UK Telecoms Provi...
WSO2Con2024 - Facilitating Broadband Switching Services for UK Telecoms Provi...WSO2
 
AzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdf
AzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdfAzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdf
AzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdfryanfarris8
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2
 
WSO2Con2024 - Hello Choreo Presentation - Kanchana
WSO2Con2024 - Hello Choreo Presentation - KanchanaWSO2Con2024 - Hello Choreo Presentation - Kanchana
WSO2Con2024 - Hello Choreo Presentation - KanchanaWSO2
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...WSO2
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...SelfMade bd
 
WSO2Con2024 - Low-Code Integration Tooling
WSO2Con2024 - Low-Code Integration ToolingWSO2Con2024 - Low-Code Integration Tooling
WSO2Con2024 - Low-Code Integration ToolingWSO2
 
WSO2CON 2024 - Unlocking the Identity: Embracing CIAM 2.0 for a Competitive A...
WSO2CON 2024 - Unlocking the Identity: Embracing CIAM 2.0 for a Competitive A...WSO2CON 2024 - Unlocking the Identity: Embracing CIAM 2.0 for a Competitive A...
WSO2CON 2024 - Unlocking the Identity: Embracing CIAM 2.0 for a Competitive A...WSO2
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024VictoriaMetrics
 
WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...
WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...
WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...WSO2
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Bert Jan Schrijver
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2
 

Recently uploaded (20)

WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
WSO2Con2024 - GitOps in Action: Navigating Application Deployment in the Plat...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
WSO2CON2024 - Why Should You Consider Ballerina for Your Next Integration
WSO2CON2024 - Why Should You Consider Ballerina for Your Next IntegrationWSO2CON2024 - Why Should You Consider Ballerina for Your Next Integration
WSO2CON2024 - Why Should You Consider Ballerina for Your Next Integration
 
WSO2CON 2024 - Building a Digital Government in Uganda
WSO2CON 2024 - Building a Digital Government in UgandaWSO2CON 2024 - Building a Digital Government in Uganda
WSO2CON 2024 - Building a Digital Government in Uganda
 
WSO2Con2024 - Facilitating Broadband Switching Services for UK Telecoms Provi...
WSO2Con2024 - Facilitating Broadband Switching Services for UK Telecoms Provi...WSO2Con2024 - Facilitating Broadband Switching Services for UK Telecoms Provi...
WSO2Con2024 - Facilitating Broadband Switching Services for UK Telecoms Provi...
 
AzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdf
AzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdfAzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdf
AzureNativeQumulo_HPC_Cloud_Native_Benchmarks.pdf
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
WSO2Con2024 - Hello Choreo Presentation - Kanchana
WSO2Con2024 - Hello Choreo Presentation - KanchanaWSO2Con2024 - Hello Choreo Presentation - Kanchana
WSO2Con2024 - Hello Choreo Presentation - Kanchana
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
WSO2Con2024 - From Blueprint to Brilliance: WSO2's Guide to API-First Enginee...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
WSO2Con2024 - Low-Code Integration Tooling
WSO2Con2024 - Low-Code Integration ToolingWSO2Con2024 - Low-Code Integration Tooling
WSO2Con2024 - Low-Code Integration Tooling
 
WSO2CON 2024 - Unlocking the Identity: Embracing CIAM 2.0 for a Competitive A...
WSO2CON 2024 - Unlocking the Identity: Embracing CIAM 2.0 for a Competitive A...WSO2CON 2024 - Unlocking the Identity: Embracing CIAM 2.0 for a Competitive A...
WSO2CON 2024 - Unlocking the Identity: Embracing CIAM 2.0 for a Competitive A...
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...
WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...
WSO2Con2024 - Navigating the Digital Landscape: Transforming Healthcare with ...
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
 

Async Testing giving you a sinking feeling

  • 1. Async tests giving you a sinking feeling?
  • 2. <span id="numbers">{{ numbers | async }}</span> <button (click)=“getNumbers()”>Subscribe</button> The Component getNumbers() { Observable.interval(1000) .subscribe(x => this.numbers.next(x)); }
  • 3. The Test it('should have a value', () => { element.querySelector(‘button’).click(); expect(numbers.textContent).toContain(‘0'); }); 😢
  • 4. The Problem of change detection <html>
  • 8. How Angular does change detection
  • 9. addEventListener() / removeEventListener() xhr request callback setTimeout() / setInterval() requestAnimationFrame() prompt() / alert() Sources of change
  • 10. ▸ Detect when async functions run ▸ Run a bit of extra code when they do ▸ Angular zone is called ngZone ZoneJS
  • 11. Running in the ngZone setTimeout(callback, delay);Zone.setTimeout(callback, delay); Zone.setTimeout = function (callback, delay) { const wrapped = function () { callback(); callAngularChangeDetection(); }; setTimeout(wrapped, delay); }
  • 12. Tragically, test code doesn’t run in the ngZone No zone for you! 😢
  • 13. it('should show the success message', (done) => { component.submit() We don’t need no automatic change detection SUBMIT SUCCESS! .then(() => { expect(getElement(‘.success’)).toBeTruthy(); done(); }); }); .then(() => fixture.detectChanges())
  • 14. getNumbers() { Observable.interval(1000) .subscribe(x => this.numbers.next(x)); } Who watches the watchers? it('should have a value', () => { element.querySelector(‘button’).click(); fixture.detectChanges(); expect(numbers.textContent).toContain('1'); }); 🤔
  • 15. - Special zone for running tests - Super powers! ▸ tick() ▸ flush()/flushMicrotasks() fakeAsync to the rescue
  • 16. tick(n): advance time n milliseconds Tick tock
  • 17. it(‘should have a value’, fakeAsync(() => { element.querySelector(‘button’).click(); tick(1000); fixture.detectChanges(); expect(element.textContent).toContain('0'); })); So close… Error: 1 periodic timer(s) still in the queue.
  • 18. Description If there are any pending timers at the end of the function, an exception will be thrown. Remain calm
  • 19. it(‘should have a value’, fakeAsync(() => { component.getNumbers(); tick(1000); fixture.detectChanges(); expect(element.textContent).toContain(‘0'); })); discardPeriodicTasks();
  • 20. Chrome 66.0.3359 (Mac OS X 10.12.6): Executed 1 of 1 SUCCESS (0.135 secs / 0.127 secs)
  • 21. ▸ flushMicrotasks() ‣ execute all remaining micro tasks ▸ flush() ▸ execute all remaining tasks ▸ fixture.whenStable() ▸ flush(), but different What if I’m not testing an interval?
  • 22. it('should set the flag', () => { let flag = false; Promise.resolve() .then(() => flag = true); expect(flag).toBe(true); }); flushMicrotasks() Expected false to be true.
  • 23. it('should set the flag', (done) => { let flag = false; Promise.resolve() .then(() => flag = true) .then(() => { expect(flag).toBe(true); done(); }); }); The old-fashioned way
  • 24. it('should set the flag', fakeAsync(() => { let flag = false; Promise.resolve() .then(() => flag = true); expect(flag).toBe(true); })); The Angular way flushMicrotasks();
  • 25. it('should set the flag', fakeAsync(() => { const time = Math.random() * 10000; let flag = false; setTimeout(() => flag = true, time); expect(flag).toBe(false); const timeElapsed = flush(); expect(flag).toBe(true); expect(timeElapsed).toBe(time); })); flush()
  • 26. fixture.whenStable(): a different way to flush it('should be true', fakeAsync(() => { fixture.whenStable() .then(() => expect(app.result).toBe(true)); })); ngOnInit() { someAsyncThing().then(() => this.result = true); }
  • 27. it('should be true', fakeAsync(() => { fixture.whenRenderingDone() .then(() => { expect(app.result).toBe(true); }); })); And one last thing…
  • 28. ▸ fixture.detectChanges() ▸ fakeAsync() zone ▸ tick(), flush() & flushMicrotasks() ▸ fixture.whenStable() & fixture.whenRenderingDone() Our weapons in the fight against async tests