Jasmine/Karma- Writing Unit Test Cases for Angular
What is Jasmine?
DOM-less simple JavaScript testing framework. Jasmine is a Behavior Driven Development testing framework for JavaScript. It does not rely on browsers, DOM, or any JavaScript framework. Thus, it's suited for websites, Node.js projects, or anywhere that JavaScript can run.
What is Karma?
Spectacular Test Runner for JavaScript. Karma is not a testing
framework, nor an assertion library. Karma just launches a HTTP server, and
generates the test runner HTML file you probably already know from your favorite
testing framework. So for testing purposes you can use pretty much anything you
like
In short,
Jasmine: Javascript
Testing Framework. Can be used as TDD
Karma: Browser
testing. Used as a Rest Runner
TESTING ANGULAR COMPONENTS
Angular
services contain UI-independent reusable business logic of the application.
myservice.service.ts
The spec file of this service has to contain:
HttpClientTestingModule and HttpTestingController for testing the
behavior of HttpClient.
The
HttpClientTestingModule includes a mock implementation of HttpClient service,
which doesn’t make the actual XHR calls, instead it provides a way to inspect
the calls attempted
The
HttpTestingController provides APIs to make sure that the HTTP calls are made,
to provide mock response to the calls and to flush the requests, so that the
subscribers of the observables would be invoked
The above
test calls the getPosts() method and expects a GET call to be made to the URL.
Then it flushes the request with the data to be returned. This is when the call
is completed and the subscribe method is called. At the end, it inspects if the
request returned the correct data.




Comments
Post a Comment