Jasmine and Karma
Unit testing JS Apps using Jasmine and Karma
Updated: 03 September 2023
Jasmine
What and Why
What
-
Javascript testing framework
-
Can be used with different languages and frameworks
-
Javascript, Node
-
Typescript, Angular
-
Ruby
-
Python
Why
-
-
-
Fast
-
Independent
-
Runs via Node or in Browser
-
Behaviour Driven Development
- Attempts to describe tests in a human readable format
Setting up a test environment
For JS
For Node
Add Jasmine as a dev dependency
Add test command to package.json
Run the test command
Writing a test suite and spec
We want to test the following helloWorld
function.
main.js
This function, when called should return 'Hello World'
test.js
4 functions
-
Define the Test Suite
-
Define a Test Spec
-
Define the Actual Value
-
Define the Comparison
Setup and Teardown
- Initialize variable that are needed for testing
- Called before all tests in a Suite are run
- Called after all tests in a Suite are run
- Called before each test Spec is run
- Called after each test Spec is run
Matchers
-
The means of comparing the
actual
andexpected
values -
Return a
boolean
indicating if a test passed or failed -
Jasmine has some pre-built Matchers
-
Custom matchers can also be defined
Running tests
-
For JS we have 2 options
-
Open
index.html
in a browser -
Run
npm test
Jasmine Demo
The following 3 files
index.html
main.js
test.js
Karma
What and Why
What
-
Test Runner for Jasmine in Angular
-
Automated running of tests
-
Does not require us to modify our code
-
Can test on multiple browser instances at once
Testing Angular Components
-
ng generate component <component>
will output:component.html
component.css
component.ts
component.spec.ts
-
Test against an instance of a component
-
Using the Angular Test Bed
Angular Test Bed
- Test behaviour that depends on Angular framework
- Test Change and Property Binding
- Import the
TestBed
,ComponentFixture
and Component to be tested
-
Configure the Test Bed’s Testing Module with the necerssary components and imports in the beforeEach
-
Reinstantiate the component before each test
-
Create a fixture and Component Instance
-
wrapper for a Component and Template
-
-
If a component has injected dependencies we can get these instances by:
Looking at the App Component
app.component.html
app.component.ts
app.component.spec.ts
Running tests with the AngularCLI
ng test
- Other Angular features can also be tested
- Services
- Components
- Classes
- Forms
- Routing
- Dependency Injection
- etc.
Karma Demo
Conclusion
- Jasmine is a relatively simple testing tool
- Easy to implement on a variety of projects
- Karma Automates testing
- Test on multiple places simultaneously
- Well incorporated into Angular