unit testing javascript: jasmine & karma intro
TRANSCRIPT
JASMINE & KARMAUnit testing your JavaScript code
Maurice de Beijer
Goals
• Understand how to write Jasmine BDD specs
• Run Jasmine specs using Karma
• Test AngularJS code with Jasmine and Karma
Jasmine
• Test suites describe the functionality
• Using a describe() function
• Can be nested
• Specs test the functionality
• Using an it() function
• Contain one or more expectations
Basic Jasmine tests
Running Jasmine tests
• We need a test runner to execute tests
• The browser
• Visual Studio with R#
• Karma
Successful test in the Browser
Matchers
• Used to verify expectations
• toBe()
• toEqual()
• toMatch()
• toBeDefined()
• toBeTruthy()
• toContain()
• toBeGreaterThan()
• toBeCloseTo()
• And more
• Can create custom matchers if needed
• You can also throw an Error to fail a test
Jasmine spies
• Can intercept function calls
• Verify if the function was called
• Optionally with specific parameters
• Can be configured to:
• Call original function
• Return a predefined result
• Call a fake function
• Throw an Error
Karma Setup
• Karma is a NodeJS application
• So first install Node.js
• Install Karma using NPM
• NPM Install Karma-Cli – g
• NPM Install Karma –save-dev
• Karma requires a configuration file
• Create using karma init
• Requires a browser to run tests
• PhantomJS is an invisible browser
• Can use multiple browser at the same time• Either in the config file
• Or by navigating to http://localhost:9876/
Successful test in Karma
Failing test in Karma
Testing AngularJS code
• Include angular-mocks.js as the last AngularJS script
• Changes some of the normal behavior
• Create Jasmine test as normal
• Add beforeEach() to load module under test
• Use the inject() function to trigger Dependency Injection
• The $controller service is the factory to create controllers
• Usually requires at least a $scope
• Other dependencies can be provided
• If not the normal DI lookup happens.
$httpBackend
• Fake implementation of the XmlHttpRequest
• Expected requests can be configured
• whenGET, whenPOST etc
• expectGET, expectPOST etc
• When... functions are soft requirement
• Do not fail a test
• Will resolve multiple time
• Expect… functions are assertions
• Fail a test is not satisfied
• Appears to the calling code as asynchronous
• Use flush() to resolve requests
Questions?
• Source code on GitHub
• https://github.com/mauricedb/Jasmine-Karma-Intro