SlideShare une entreprise Scribd logo
1  sur  47
Télécharger pour lire hors ligne
AngularJS
Unit Testing
Karma + Jasmine
1
2
Karma - Test Runner
Jasmine - Testing Framework
Setting up Unit Test on AngularJS
Debugging your Unit Tests
Integration with CI & Slack
Testing & Coverage Reports
Karma - Test Runner
for AngularJS
3
4
Karma - Test Runner
- Able to spawn a web server and run tests against multiple browsers
> What is Karma ?
- Simple configuration & instant feedback from tests
- Easy for debugging (directly in Chrome)
- Simple integration with CI Tools (eg. Jenkins)
> Why use Karma ?
- Describe tests with Jasmine, Mocha, QUunit and etc.
- Preferred test-runner for AngularJS Project
> How to config or setup?
- Stay tune for the following slides or Jump over there
Refer to https://github.com/karma-runner/karma
Jasmine - Testing Framework
Behaviour-Driven JavaScript
5
Jasmine - Testing Framework
6
> What is Jasmine ?
- A behaviour driven framework for testing JS code
- Does not depend on other JS framework
- Does not require a DOM (Document Object Model)
- It has clean, obvious syntax for writing tests
Expectation MatcherSuite
Spec
Refer to http://jasmine.github.io/2.4/introduction.html
7
> Suites : describe() your tests
> Specs : it() should do this/should have value
Jasmine - Few things to take note
- Used for describing your tests and wrap block of codes
- Can be nested under another describe() to further divide it
- Contain 1 or more specs & beforeEach()/afterEach() function
- Describe your individual tests
- Divide your test suites into sub components
- Usually will be a sentence to describe what it will do
- Both of the describe() and it() are function and can contain any
executable code necessary to implement the test.
- Variables declared inside describe() are available to any it() block
inside the same suite
8
> Expectations : expect() actual value to equal expected value
Jasmine - Few things to take note
- Built with a function “expect” which takes the actual value, and
- chained with a Matcher function which takes the expected value
> Matchers : match the expected value
- Built in matcher by Jasmine or refer to custom matchers
Setting Up Unit Test
on AngularJS
Reference : Click Me & Me
9
10
Step 1 - Install Required Dependencies
> Install karma-cli and phantomjs
> Copy the following into package.json and run “npm install”
"devDependencies": {
"angular-mocks": "^1.5.5",
"jasmine-core": "^2.4.1",
"karma": "^0.13.22",
"karma-chrome-launcher": "^1.0.1",
"karma-coverage": "^1.0.0",
"karma-jasmine": "^1.0.2",
"karma-junit-reporter": "^1.0.0",
"karma-mocha-reporter": "^2.0.3",
"karma-phantomjs-launcher": “^1.0.0",
}
inject & mock angular services into unit test
Chrome launcher for karma
Generate coverage reports
Generate JUnit report for Jenkins
Generate Mocha report for view
in command line
PhantomJS Browser (without GUI)
- npm install -g karma-cli
- npm install –g phantomjs
For running karma using command line tool
For running PhantomJS browser
11
Step 2 - Configure karma.conf.js
> Run “karma init” to generate initial karma.conf.js file
- Press enter for all prompts (can be modified later on)
> Add in files/patterns to be loaded in browser
Required library files
Your source codes
Your test specs
12
Step 2 - Configure karma.conf.js
> Add source code’s path for generating karma coverage report
> Add in plugins to be used
preprocessors: {
'www/js/**/*.js': ['coverage']
},
Add 2 browsers
plugins: [
'karma-jasmine',
'karma-mocha-reporter',
'karma-phantomjs-launcher',
'karma-chrome-launcher',
'karma-coverage'
],
Use mocha reporter
browsers: ['Chrome','PhantomJS'],
> Register browsers list
13
Step 2 - Configure karma.conf.js
> Register reporters to be used
> Configuration for mochaReporter and coverageReporter
reporters: ['mocha','coverage'],
mochaReporter: {
colors: {
success: 'green',
info: 'cyan',
warning: 'orange',
error: 'red'
}
},
coverageReporter : {
type : 'html',
dir : 'target/coverage-reports/'
},
> Other configurations
autoWatch: true,
singleRun: false,
concurrency: Infinity
Auto watch for file changes
singleRun have to be true if use Jenkins, else set to false
Browsers will be started simultaneously
14
Step 3 - Writing test specifications
An outer suite to describe your app
beforeEach() will be executed before
running every expect() inside it()
1
2
3
4
5
6
Load the module “app” Inject angular services into the tests
using angular-mocks feature
Create the scope & pass
into the controller
An inner suite to group block of specs
15
Step 4 - Run your unit test :p Use ‘karma start’ or ‘karma start
karma.conf.js’ to start karma
Starting 2 browsers
Outer & inner suite name
Specification name
2 browser * 2 tests = 4 tests
Click on “debug” can go
into debug mode
Debugging your Unit Tests
16
Using Chrome
17
> Place a debugger statement into your spec (only works in chrome)
Ways to debug your tests
- Press the debug button as shown in previous slide
- When new tab opened, open Inspect (Cmd+Opt+I or Ctrl+Shift+I)
- Press F5 to refresh the page, and it will stop at that “debugger” line
18
> Put breakpoints in your tests
Ways to debug your tests
- Press the debug button as shown in previous slide
- When new tab opened, open Inspect (Cmd+Opt+I or Ctrl+Shift+I)
- Search for your tests spec.js and place breakpoints
- Press F5 to refresh the page, and it will stop at first breakpoint you put
- Then, use F8 to move to next breakpoint
Testing & Coverage Reports
19
For Karma
20
Mocha Reporter
> Mocha reporter is used when run test in local environment & command line
- Test result with all passed tests
- Test result with failed tests
> Other reporters can be found on NPM website
21
Karma Coverage Reporter
> Coverage reporter helps to generate the code coverage for your tests
- It will determine how many percentage of your code is covered for
testing (eg. Statements, branches, functions & lines)
- Refer to karma website on configuration for coverage reporter
22
Karma Coverage Reporter
This line indicates that the statement
is not covered in test
If path is not taken
Integration with CI & Slack
23
CI = Jenkins
24
Configuration on karma.jenkins.conf.js
> Duplicate karma.conf.js and rename as karma.jenkins.conf.js
> Modify plugins to be used in karma.jenkins.conf.js
browsers: ['PhantomJS'],
> Register browsers list
> In package.json, add in scripts so we can run “npm test” in Jenkins later
"scripts": { "test": "karma start karma.jenkins.conf.js" },
Change mocha reporter to junit reporter in
order to output test results to jenkins
plugins: [
'karma-jasmine',
'karma-phantomjs-launcher',
'karma-junit-reporter',
'karma-coverage',
],
Only use phantomjs browser
25
Configuration on karma.jenkins.conf.js
> Register reporters to be used
> Modify coverageReporter & replace mochaReporter with junitReporter
reporters: ['progress', 'junit', 'coverage'],
> Other configurations
autoWatch: true,
singleRun: true,
concurrency: Infinity
Set singleRun to true so it only execute once in jenkins
coverageReporter : {
type : cobertura',
dir : 'target/coverage-reports/'
},
Change type from “html” to “cobertura”
so Jenkins can understand
junitReporter : {
outputDir: 'target/surefire-reports',
outputFile: undefined,
},
26
Install Jenkins & its Plugins
> Download & Install Jenkins at jenkins.io
> Install Jenkins Plugin (Manage Jenkins > Manage Plugins)
- Install Cobertura Plugin (for generate coverage reports)
- v1.65 or v2.3 also workable
- Install Git Plugin (to pull .git repository)
27
Configuration on Jenkins
> Create a new item
> Select freestyle project and enter name
28
Configuration on Jenkins
> Go to your project > configure
- Under Source Code Management, select “Git"
- Enter your Git Repository URL
29
Configuration on Jenkins
- Under Build Triggers, tick on “Poll SCM"
- Do not fill anything in Schedule (so it will not poll every time)
#!/bin/sh
curl
http://localhost:8080/git/notifyCommit?url={{Your_
Project_Repository_URL}}
- Create a new file “post-commit” in “YouProject/.git/hooks” folder
- This is to trigger the Jenkins build after we commit to git
30
Configuration on Jenkins
- Under Build, click “Add Build Step” and select “Execute shell”
- Select “Execute Windows batch command” if use windows
- In command, enter “call npm install” & “call npm test”
31
Configuration on Jenkins
- Under Post Build Action, select “Publish Cobertura Coverage Report” and
“Publish JUnit test result report”
- Then, enter the url pattern as shown in the image
32
Integrate Slack with Jenkins
> To integrate with slack, go to Manage Jenkins
33
> Then Manage Plugins & search for Slack Notification Plugin
Integrate Slack with Jenkins
34
> Then go to Configure System > Global Slack Notifier Settings
Integrate Slack with Jenkins
Go to https://slack.com/apps/search?q=jenkins and add Jenkins
to your slack in order to obtain Integration Token
35
> Select your Jenkins project > Configure > Add Post-build Actions
Integrate Slack with Jenkins
36
> Tick on the events you want to be notified
Integrate Slack with Jenkins
> Remember to press “Save” after all changes !!
37
> Select your Project > Build Now, then it will start running
Running your Jenkins build
38
> After run successfully, your slack will be notified and reports generated
Running your Jenkins build
39
> Notification on slack after successful build
Running your Jenkins build
40
> Click on “Coverage Report” to view Cobertura Coverage report
View Coverage Report
41
> Click on “Test Result” to view JUnit Test Result
View Test Results
42
> Make some changes to your AngularJS project and commit to git
Triggering Jenkins Build on commit
43
> Go to your Jenkins project > Click on Build #5 (Trigger by commit)
Running your Jenkins build
44
> Go to your Jenkins project > Click on Build #4 (Build Manually)
Running your Jenkins build
References
45
46
Mocking Dependencies in AngularJS Tests
References List
Unit Testing in AngularJS: Services, Controllers & Providers
Advanced Testing and Debugging in AngularJS
Automatically triggering a Jenkins build on Git commit
> For Triggering build on Jenkins
> For Unit Testing
http://karma-runner.github.io/0.8/plus/Jenkins-CI.html
> For Integration of Jenkins with Karma
THE END
Thanks for viewing ^^
47

Contenu connexe

Tendances

Tendances (20)

AngularJS Unit Testing
AngularJS Unit TestingAngularJS Unit Testing
AngularJS Unit Testing
 
Unit testing JavaScript: Jasmine & karma intro
Unit testing JavaScript: Jasmine & karma introUnit testing JavaScript: Jasmine & karma intro
Unit testing JavaScript: Jasmine & karma intro
 
Quick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmineQuick tour to front end unit testing using jasmine
Quick tour to front end unit testing using jasmine
 
Jquery- One slide completing all JQuery
Jquery- One slide completing all JQueryJquery- One slide completing all JQuery
Jquery- One slide completing all JQuery
 
JavaScript TDD with Jasmine and Karma
JavaScript TDD with Jasmine and KarmaJavaScript TDD with Jasmine and Karma
JavaScript TDD with Jasmine and Karma
 
Karma - JS Test Runner
Karma - JS Test RunnerKarma - JS Test Runner
Karma - JS Test Runner
 
Angular testing
Angular testingAngular testing
Angular testing
 
Angular Unit Testing
Angular Unit TestingAngular Unit Testing
Angular Unit Testing
 
Advanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit TestingAdvanced Jasmine - Front-End JavaScript Unit Testing
Advanced Jasmine - Front-End JavaScript Unit Testing
 
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
JavaScript Test-Driven Development with Jasmine 2.0 and Karma JavaScript Test-Driven Development with Jasmine 2.0 and Karma
JavaScript Test-Driven Development with Jasmine 2.0 and Karma
 
Test-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsTest-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS Applications
 
Angular JS Unit Testing - Overview
Angular JS Unit Testing - OverviewAngular JS Unit Testing - Overview
Angular JS Unit Testing - Overview
 
Test Driven Development with JavaFX
Test Driven Development with JavaFXTest Driven Development with JavaFX
Test Driven Development with JavaFX
 
Painless JavaScript Testing with Jest
Painless JavaScript Testing with JestPainless JavaScript Testing with Jest
Painless JavaScript Testing with Jest
 
vJUG - The JavaFX Ecosystem
vJUG - The JavaFX EcosystemvJUG - The JavaFX Ecosystem
vJUG - The JavaFX Ecosystem
 
Jasmine BDD for Javascript
Jasmine BDD for JavascriptJasmine BDD for Javascript
Jasmine BDD for Javascript
 
Unit-testing and E2E testing in JS
Unit-testing and E2E testing in JSUnit-testing and E2E testing in JS
Unit-testing and E2E testing in JS
 
Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015Unit Testing Express and Koa Middleware in ES2015
Unit Testing Express and Koa Middleware in ES2015
 
JavaFX8 TestFX - CDI
JavaFX8   TestFX - CDIJavaFX8   TestFX - CDI
JavaFX8 TestFX - CDI
 
Testing ansible roles with molecule
Testing ansible roles with moleculeTesting ansible roles with molecule
Testing ansible roles with molecule
 

En vedette

AngularJs Style Guide
AngularJs Style GuideAngularJs Style Guide
AngularJs Style Guide
Chiew Carol
 
Slaven tomac unit testing in angular js
Slaven tomac   unit testing in angular jsSlaven tomac   unit testing in angular js
Slaven tomac unit testing in angular js
Slaven Tomac
 
TDD, unit testing and java script testing frameworks workshop
TDD, unit testing and java script testing frameworks workshopTDD, unit testing and java script testing frameworks workshop
TDD, unit testing and java script testing frameworks workshop
Sikandar Ahmed
 

En vedette (19)

Automated Testing With Jasmine, PhantomJS and Jenkins
Automated Testing With Jasmine, PhantomJS and JenkinsAutomated Testing With Jasmine, PhantomJS and Jenkins
Automated Testing With Jasmine, PhantomJS and Jenkins
 
Jasmine
JasmineJasmine
Jasmine
 
Detangling Your JavaScript
Detangling Your JavaScriptDetangling Your JavaScript
Detangling Your JavaScript
 
Javascript Tests with Jasmine for Front-end Devs
Javascript Tests with Jasmine for Front-end DevsJavascript Tests with Jasmine for Front-end Devs
Javascript Tests with Jasmine for Front-end Devs
 
AngularJs Style Guide
AngularJs Style GuideAngularJs Style Guide
AngularJs Style Guide
 
Quick Tour to Front-End Unit Testing Using Jasmine
Quick Tour to Front-End Unit Testing Using JasmineQuick Tour to Front-End Unit Testing Using Jasmine
Quick Tour to Front-End Unit Testing Using Jasmine
 
EasyTest Test Automation Tool Introduction
EasyTest Test Automation Tool IntroductionEasyTest Test Automation Tool Introduction
EasyTest Test Automation Tool Introduction
 
AngularJS Testing Strategies
AngularJS Testing StrategiesAngularJS Testing Strategies
AngularJS Testing Strategies
 
Testing angular js
Testing angular jsTesting angular js
Testing angular js
 
Slaven tomac unit testing in angular js
Slaven tomac   unit testing in angular jsSlaven tomac   unit testing in angular js
Slaven tomac unit testing in angular js
 
Jasmine - why JS tests don't smell fishy
Jasmine - why JS tests don't smell fishyJasmine - why JS tests don't smell fishy
Jasmine - why JS tests don't smell fishy
 
Test-Driven Development with TypeScript+Jasmine+AngularJS
Test-Driven Development with TypeScript+Jasmine+AngularJSTest-Driven Development with TypeScript+Jasmine+AngularJS
Test-Driven Development with TypeScript+Jasmine+AngularJS
 
Jasmine - A BDD test framework for JavaScript
Jasmine - A BDD test framework for JavaScriptJasmine - A BDD test framework for JavaScript
Jasmine - A BDD test framework for JavaScript
 
TDD, unit testing and java script testing frameworks workshop
TDD, unit testing and java script testing frameworks workshopTDD, unit testing and java script testing frameworks workshop
TDD, unit testing and java script testing frameworks workshop
 
AngularJS Testing
AngularJS TestingAngularJS Testing
AngularJS Testing
 
Angular 2 - What's new and what's different
Angular 2 - What's new and what's differentAngular 2 - What's new and what's different
Angular 2 - What's new and what's different
 
Jasmine Sandler Client Case Studies- Digital Marketing Consultant - Social Me...
Jasmine Sandler Client Case Studies- Digital Marketing Consultant - Social Me...Jasmine Sandler Client Case Studies- Digital Marketing Consultant - Social Me...
Jasmine Sandler Client Case Studies- Digital Marketing Consultant - Social Me...
 
JAVASCRIPT Test Driven Development & Jasmine
JAVASCRIPT Test Driven Development & JasmineJAVASCRIPT Test Driven Development & Jasmine
JAVASCRIPT Test Driven Development & Jasmine
 
TDD Basics with Angular.js and Jasmine
TDD Basics with Angular.js and JasmineTDD Basics with Angular.js and Jasmine
TDD Basics with Angular.js and Jasmine
 

Similaire à AngularJS Unit Test

Enterprise Build And Test In The Cloud
Enterprise Build And Test In The CloudEnterprise Build And Test In The Cloud
Enterprise Build And Test In The Cloud
Carlos Sanchez
 
anugula2setupbyshubham
anugula2setupbyshubhamanugula2setupbyshubham
anugula2setupbyshubham
Shubham Verma
 
Integrate UFT with Jenkins Guide
Integrate UFT with Jenkins GuideIntegrate UFT with Jenkins Guide
Integrate UFT with Jenkins Guide
Yu Tao Zhang
 

Similaire à AngularJS Unit Test (20)

Protractor framework architecture with example
Protractor framework architecture with exampleProtractor framework architecture with example
Protractor framework architecture with example
 
Ng2 cli
Ng2 cliNg2 cli
Ng2 cli
 
How to make a Load Testing with Visual Studio 2012
How to make a Load Testing with Visual Studio 2012How to make a Load Testing with Visual Studio 2012
How to make a Load Testing with Visual Studio 2012
 
Enterprise Build And Test In The Cloud
Enterprise Build And Test In The CloudEnterprise Build And Test In The Cloud
Enterprise Build And Test In The Cloud
 
Testing your application on Google App Engine
Testing your application on Google App EngineTesting your application on Google App Engine
Testing your application on Google App Engine
 
Testing Your Application On Google App Engine
Testing Your Application On Google App EngineTesting Your Application On Google App Engine
Testing Your Application On Google App Engine
 
Jenkins Tutorial.pdf
Jenkins Tutorial.pdfJenkins Tutorial.pdf
Jenkins Tutorial.pdf
 
Using Jenkins and Jmeter to build a scalable Load Testing solution
Using Jenkins and Jmeter to build a scalable Load Testing solutionUsing Jenkins and Jmeter to build a scalable Load Testing solution
Using Jenkins and Jmeter to build a scalable Load Testing solution
 
How to Implement Micro Frontend Architecture using Angular Framework
How to Implement Micro Frontend Architecture using Angular FrameworkHow to Implement Micro Frontend Architecture using Angular Framework
How to Implement Micro Frontend Architecture using Angular Framework
 
Codeception presentation
Codeception presentationCodeception presentation
Codeception presentation
 
Protractor Testing Automation Tool Framework / Jasmine Reporters
Protractor Testing Automation Tool Framework / Jasmine ReportersProtractor Testing Automation Tool Framework / Jasmine Reporters
Protractor Testing Automation Tool Framework / Jasmine Reporters
 
Performance Testing - Apache Benchmark, JMeter
Performance Testing  - Apache Benchmark, JMeterPerformance Testing  - Apache Benchmark, JMeter
Performance Testing - Apache Benchmark, JMeter
 
Javascript tdd byandreapaciolla
Javascript tdd byandreapaciollaJavascript tdd byandreapaciolla
Javascript tdd byandreapaciolla
 
Dive into Angular, part 5: Experience
Dive into Angular, part 5: ExperienceDive into Angular, part 5: Experience
Dive into Angular, part 5: Experience
 
anugula2setupbyshubham
anugula2setupbyshubhamanugula2setupbyshubham
anugula2setupbyshubham
 
How to use_cucumber_rest-assured_api_framework
How to use_cucumber_rest-assured_api_frameworkHow to use_cucumber_rest-assured_api_framework
How to use_cucumber_rest-assured_api_framework
 
Glassfish JEE Server Administration - The Enterprise Server
Glassfish JEE Server Administration - The Enterprise ServerGlassfish JEE Server Administration - The Enterprise Server
Glassfish JEE Server Administration - The Enterprise Server
 
Integrate UFT with Jenkins Guide
Integrate UFT with Jenkins GuideIntegrate UFT with Jenkins Guide
Integrate UFT with Jenkins Guide
 
Automated Acceptance Testing Example
Automated Acceptance Testing ExampleAutomated Acceptance Testing Example
Automated Acceptance Testing Example
 
Introduction To Programming IP5
Introduction To Programming IP5Introduction To Programming IP5
Introduction To Programming IP5
 

Dernier

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Dernier (20)

Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 

AngularJS Unit Test

  • 2. 2 Karma - Test Runner Jasmine - Testing Framework Setting up Unit Test on AngularJS Debugging your Unit Tests Integration with CI & Slack Testing & Coverage Reports
  • 3. Karma - Test Runner for AngularJS 3
  • 4. 4 Karma - Test Runner - Able to spawn a web server and run tests against multiple browsers > What is Karma ? - Simple configuration & instant feedback from tests - Easy for debugging (directly in Chrome) - Simple integration with CI Tools (eg. Jenkins) > Why use Karma ? - Describe tests with Jasmine, Mocha, QUunit and etc. - Preferred test-runner for AngularJS Project > How to config or setup? - Stay tune for the following slides or Jump over there Refer to https://github.com/karma-runner/karma
  • 5. Jasmine - Testing Framework Behaviour-Driven JavaScript 5
  • 6. Jasmine - Testing Framework 6 > What is Jasmine ? - A behaviour driven framework for testing JS code - Does not depend on other JS framework - Does not require a DOM (Document Object Model) - It has clean, obvious syntax for writing tests Expectation MatcherSuite Spec Refer to http://jasmine.github.io/2.4/introduction.html
  • 7. 7 > Suites : describe() your tests > Specs : it() should do this/should have value Jasmine - Few things to take note - Used for describing your tests and wrap block of codes - Can be nested under another describe() to further divide it - Contain 1 or more specs & beforeEach()/afterEach() function - Describe your individual tests - Divide your test suites into sub components - Usually will be a sentence to describe what it will do - Both of the describe() and it() are function and can contain any executable code necessary to implement the test. - Variables declared inside describe() are available to any it() block inside the same suite
  • 8. 8 > Expectations : expect() actual value to equal expected value Jasmine - Few things to take note - Built with a function “expect” which takes the actual value, and - chained with a Matcher function which takes the expected value > Matchers : match the expected value - Built in matcher by Jasmine or refer to custom matchers
  • 9. Setting Up Unit Test on AngularJS Reference : Click Me & Me 9
  • 10. 10 Step 1 - Install Required Dependencies > Install karma-cli and phantomjs > Copy the following into package.json and run “npm install” "devDependencies": { "angular-mocks": "^1.5.5", "jasmine-core": "^2.4.1", "karma": "^0.13.22", "karma-chrome-launcher": "^1.0.1", "karma-coverage": "^1.0.0", "karma-jasmine": "^1.0.2", "karma-junit-reporter": "^1.0.0", "karma-mocha-reporter": "^2.0.3", "karma-phantomjs-launcher": “^1.0.0", } inject & mock angular services into unit test Chrome launcher for karma Generate coverage reports Generate JUnit report for Jenkins Generate Mocha report for view in command line PhantomJS Browser (without GUI) - npm install -g karma-cli - npm install –g phantomjs For running karma using command line tool For running PhantomJS browser
  • 11. 11 Step 2 - Configure karma.conf.js > Run “karma init” to generate initial karma.conf.js file - Press enter for all prompts (can be modified later on) > Add in files/patterns to be loaded in browser Required library files Your source codes Your test specs
  • 12. 12 Step 2 - Configure karma.conf.js > Add source code’s path for generating karma coverage report > Add in plugins to be used preprocessors: { 'www/js/**/*.js': ['coverage'] }, Add 2 browsers plugins: [ 'karma-jasmine', 'karma-mocha-reporter', 'karma-phantomjs-launcher', 'karma-chrome-launcher', 'karma-coverage' ], Use mocha reporter browsers: ['Chrome','PhantomJS'], > Register browsers list
  • 13. 13 Step 2 - Configure karma.conf.js > Register reporters to be used > Configuration for mochaReporter and coverageReporter reporters: ['mocha','coverage'], mochaReporter: { colors: { success: 'green', info: 'cyan', warning: 'orange', error: 'red' } }, coverageReporter : { type : 'html', dir : 'target/coverage-reports/' }, > Other configurations autoWatch: true, singleRun: false, concurrency: Infinity Auto watch for file changes singleRun have to be true if use Jenkins, else set to false Browsers will be started simultaneously
  • 14. 14 Step 3 - Writing test specifications An outer suite to describe your app beforeEach() will be executed before running every expect() inside it() 1 2 3 4 5 6 Load the module “app” Inject angular services into the tests using angular-mocks feature Create the scope & pass into the controller An inner suite to group block of specs
  • 15. 15 Step 4 - Run your unit test :p Use ‘karma start’ or ‘karma start karma.conf.js’ to start karma Starting 2 browsers Outer & inner suite name Specification name 2 browser * 2 tests = 4 tests Click on “debug” can go into debug mode
  • 16. Debugging your Unit Tests 16 Using Chrome
  • 17. 17 > Place a debugger statement into your spec (only works in chrome) Ways to debug your tests - Press the debug button as shown in previous slide - When new tab opened, open Inspect (Cmd+Opt+I or Ctrl+Shift+I) - Press F5 to refresh the page, and it will stop at that “debugger” line
  • 18. 18 > Put breakpoints in your tests Ways to debug your tests - Press the debug button as shown in previous slide - When new tab opened, open Inspect (Cmd+Opt+I or Ctrl+Shift+I) - Search for your tests spec.js and place breakpoints - Press F5 to refresh the page, and it will stop at first breakpoint you put - Then, use F8 to move to next breakpoint
  • 19. Testing & Coverage Reports 19 For Karma
  • 20. 20 Mocha Reporter > Mocha reporter is used when run test in local environment & command line - Test result with all passed tests - Test result with failed tests > Other reporters can be found on NPM website
  • 21. 21 Karma Coverage Reporter > Coverage reporter helps to generate the code coverage for your tests - It will determine how many percentage of your code is covered for testing (eg. Statements, branches, functions & lines) - Refer to karma website on configuration for coverage reporter
  • 22. 22 Karma Coverage Reporter This line indicates that the statement is not covered in test If path is not taken
  • 23. Integration with CI & Slack 23 CI = Jenkins
  • 24. 24 Configuration on karma.jenkins.conf.js > Duplicate karma.conf.js and rename as karma.jenkins.conf.js > Modify plugins to be used in karma.jenkins.conf.js browsers: ['PhantomJS'], > Register browsers list > In package.json, add in scripts so we can run “npm test” in Jenkins later "scripts": { "test": "karma start karma.jenkins.conf.js" }, Change mocha reporter to junit reporter in order to output test results to jenkins plugins: [ 'karma-jasmine', 'karma-phantomjs-launcher', 'karma-junit-reporter', 'karma-coverage', ], Only use phantomjs browser
  • 25. 25 Configuration on karma.jenkins.conf.js > Register reporters to be used > Modify coverageReporter & replace mochaReporter with junitReporter reporters: ['progress', 'junit', 'coverage'], > Other configurations autoWatch: true, singleRun: true, concurrency: Infinity Set singleRun to true so it only execute once in jenkins coverageReporter : { type : cobertura', dir : 'target/coverage-reports/' }, Change type from “html” to “cobertura” so Jenkins can understand junitReporter : { outputDir: 'target/surefire-reports', outputFile: undefined, },
  • 26. 26 Install Jenkins & its Plugins > Download & Install Jenkins at jenkins.io > Install Jenkins Plugin (Manage Jenkins > Manage Plugins) - Install Cobertura Plugin (for generate coverage reports) - v1.65 or v2.3 also workable - Install Git Plugin (to pull .git repository)
  • 27. 27 Configuration on Jenkins > Create a new item > Select freestyle project and enter name
  • 28. 28 Configuration on Jenkins > Go to your project > configure - Under Source Code Management, select “Git" - Enter your Git Repository URL
  • 29. 29 Configuration on Jenkins - Under Build Triggers, tick on “Poll SCM" - Do not fill anything in Schedule (so it will not poll every time) #!/bin/sh curl http://localhost:8080/git/notifyCommit?url={{Your_ Project_Repository_URL}} - Create a new file “post-commit” in “YouProject/.git/hooks” folder - This is to trigger the Jenkins build after we commit to git
  • 30. 30 Configuration on Jenkins - Under Build, click “Add Build Step” and select “Execute shell” - Select “Execute Windows batch command” if use windows - In command, enter “call npm install” & “call npm test”
  • 31. 31 Configuration on Jenkins - Under Post Build Action, select “Publish Cobertura Coverage Report” and “Publish JUnit test result report” - Then, enter the url pattern as shown in the image
  • 32. 32 Integrate Slack with Jenkins > To integrate with slack, go to Manage Jenkins
  • 33. 33 > Then Manage Plugins & search for Slack Notification Plugin Integrate Slack with Jenkins
  • 34. 34 > Then go to Configure System > Global Slack Notifier Settings Integrate Slack with Jenkins Go to https://slack.com/apps/search?q=jenkins and add Jenkins to your slack in order to obtain Integration Token
  • 35. 35 > Select your Jenkins project > Configure > Add Post-build Actions Integrate Slack with Jenkins
  • 36. 36 > Tick on the events you want to be notified Integrate Slack with Jenkins > Remember to press “Save” after all changes !!
  • 37. 37 > Select your Project > Build Now, then it will start running Running your Jenkins build
  • 38. 38 > After run successfully, your slack will be notified and reports generated Running your Jenkins build
  • 39. 39 > Notification on slack after successful build Running your Jenkins build
  • 40. 40 > Click on “Coverage Report” to view Cobertura Coverage report View Coverage Report
  • 41. 41 > Click on “Test Result” to view JUnit Test Result View Test Results
  • 42. 42 > Make some changes to your AngularJS project and commit to git Triggering Jenkins Build on commit
  • 43. 43 > Go to your Jenkins project > Click on Build #5 (Trigger by commit) Running your Jenkins build
  • 44. 44 > Go to your Jenkins project > Click on Build #4 (Build Manually) Running your Jenkins build
  • 46. 46 Mocking Dependencies in AngularJS Tests References List Unit Testing in AngularJS: Services, Controllers & Providers Advanced Testing and Debugging in AngularJS Automatically triggering a Jenkins build on Git commit > For Triggering build on Jenkins > For Unit Testing http://karma-runner.github.io/0.8/plus/Jenkins-CI.html > For Integration of Jenkins with Karma
  • 47. THE END Thanks for viewing ^^ 47