
What is Jasmine
•Jasmine is an open-source JavaScript testing framework.
•JavaScript testing framework provides building blocks to write JavaScript unit test cases so each line of JavaScript statement is properly unit tested.
•It is used to test any type of JavaScript application.
•Jasmine is a BDD (Behavior Driven Development)
In BDD Test are written in Non-technical language so everyone can understand it easily.
BDD manly focus on the testing the behavior of code rather than implementation.
What is Karma
•Karma is a testing automation tool created by the Angular JS team.
•Karma is Open source tool.
•Karma is a tool made on top of NodeJS to run JavaScript test cases.
•This is not a testing framework like Jasmine or Mocha or Chai etc
•It only allows us to run JavaScript test cases written using testing frameworks like Jasmine.
•Karma allow us to execute the test cases on any browsers.
•Karma runs JavaScript test cases against real browsers through Command Line Interface (CLI) rather than virtual browser and DOM. Since, DOM rendering across browsers vary, so for correctness of the test report it uses real browsers.
•It can be configured what all browsers need to be used while running Karma.
•Karma can we configured with continuous integration tools like Travis, Jenkin etc.
•
•The flow of how the test run is shown below
•The Angular testing package includes two utilities called TestBed and async.
•
•TestBed is the main Angular utility package.
•
•The describe container contains different blocks (it, beforeEach, xit, etc.).
•
•beforeEach runs before any other block. Other blocks do not depend on each other to run.
Learn how to run Angular unit test cases with Jasmine and Karma, using describe and it blocks, configure testing module, and run the ng test command.
Configure Jasmine and Karma in an Angular project to run unit tests in the browser. Explore the Karma configuration, angular.json, and package.json dependencies that support test setup and reporting.
Learn to exclude specific angular unit tests from execution using the x prefix before describe or it blocks, enabling selective test runs with Jasmine and Karma.
•What are matchers
•Matchers are nothing but compare functions to actually compare the expected and actual result in the test specs.
•Matchers are the JavaScript function that does a Boolean comparison between an actual output and an expected output.
•There are two type of matchers Inbuilt matcher and Custom matchers.
••Custom Matchers
•The matchers which are not present in the inbuilt system library of Jasmine is called as custom matcher. Custom matcher needs to be defined explicitly().
Explore when to use toBe versus toEqual in Jasmine for Angular unit tests, demonstrating primitive comparisons with toBe and deep equality with toEqual for objects.
Explore how to use Jasmine matchers like toBe(true), toBeTrue(), toBeFalsy(), and toBeFalse() in Angular unit tests; learn how they validate boolean values and ensure correct equality between actual and expected.
Demonstrate using Jasmine matchers toBeGreaterThan, toBeGreaterThanOrEqual, toBeLessThan, and toBeLessThanOrEqual in Angular unit tests with Jasmine and Karma.
Explore how to use toMatch and toBeCloseTo in Jasmine for Angular unit tests, demonstrating regex matching and numeric precision checks with examples.
Learn how toBeDefined and toBeUndefined in Jasmine help verify whether objects, variables, and functions are initialized in Angular unit tests.
Learn how to use Jasmine matchers such as toBeNull, toContain, toBeNaN, and toBePositiveInfinity and toBeNegativeInfinity to handle null, undefined, and infinity scenarios in tests.
Explore how beforeAll and afterAll run once for a describe block in Jasmine, bracketing the test suite, and see how this contrasts with beforeEach and afterEach.
Explore the arrange-act-assert pattern for unit tests in angular, illustrating how to initialize a component, perform an action, and assert expected results using jasmine and karma.
Learn how to use TestBed and ComponentFixture in Angular unit tests to create components, inject services, configure testing module, and interact with templates and change detection using Jasmine and Karma.
Master spy on techniques to mock and stub angular methods in unit tests, and learn the difference between spy on, mock, and stub for verifying calls and return values.
Explore how the Angular debug element represents native DOM elements, exposes event handlers, and lets you trigger click events to verify changes in unit tests using Jasmine and Karma.
Learn to spy on private methods in Angular unit tests using the any keyword, validating private calculate and show name methods with Jasmine and Karma.
Learn to write an Angular unit test for property binding and interpolation, ensuring read-only attributes reflect boolean values in the DOM and validating binding behavior with Jasmine and Karma.
Develop unit tests for ngClass and ngStyle bindings in Angular, verifying color changes based on a numeric condition using fixture and debugElement with Jasmine and Karma.
Learn to write a unit test for Angular attribute binding using Jasmine and Karma; identify the element by id, access the attribute, and verify the binding.
Learn to write unit tests for Angular event binding using Jasmine and Karma, covering click, on change, and textbox input events, DOM element selection, dispatching events, and assertions.
Learn to write Angular unit tests for ngSwitch, verifying selected options by querying elements, counting children, and asserting values for one and two cases using Jasmine and Karma.
Write Angular unit tests for ngFor using Jasmine and Karma to verify both simple and complex color lists, including index-based class bindings and color name and id rendering.
•Dependency injection, or DI, is a design pattern in which a class requests dependencies from external sources rather than creating them.
• Angular's DI framework provides dependencies to a class upon instantiation. Use Angular DI to increase flexibility and modularity in your applications.
•TestBed is a mock environment to run Angular component tests without the browser.
•The TestBed is the first and largest of the Angular testing utilities. It creates an Angular testing module — a @NgModule class — that you configure with the configureTestingModule method to produce the module environment for the class you want to test.
•
•Using testbed get method
•Using inject method
•By overriding component provider
•Pipes are referred as filters.
•It helps to transform data and manage data within interpolation, denoted by {{ | }}.
•It accepts data, arrays, integers and strings as inputs which are separated by ‘|’ symbol.
•
•command “ng generate pipe fileSize”
Learn to write a unit test for Angular routing using Jasmine and Karma, configure the router testing module, and assert default navigation to the student component.
•Lazy loading is a technology of angular that allows you to load JavaScript components when a specific route is activated. It improves application load time speed by splitting the application into many bundles. When the user navigates by the app, bundles are loaded as needed.
•Lazy loading helps to keep the bundle size small, which helps reduce load times. We must use the class decorator to create an Angular
•module @NgModule, and the decorator uses a metadata object that defines the module.
•The main properties are:
•import: Components of this module are used with Array with other modules.
•Declarations: It receives an array of the components.
•Export: Defines an array of components, directives, and pipes used by other modules.
•Provider: Declares services that are available to the entire application if it is a root module.
SpyNgModuleFactoryLoader Doesn't work anymore in angular 13/14 since NgModuleFactoryLoader is deprecated and removed from Angular.
Replace SpyNgModuleFactoryLoader with NgModule
we can use ngModule instead of it like below
it('Lazy loading test case', fakeAsync(() = >{ const lazyloder = TestBed.inject(NgModule); lazyloder.stubbedModules = {lazymodule:LazyModule}; objRouter.navigateByUrl('/employeelist'); tick(); fixture.detectChanges(); expect(location.path()).toBe('/employeelist'); }));
•httpClientTestingModule is used to test the http methods using httpclient.
•httpClientTestingModule inject HttpTestingController.
•The HttpClientTestingModule allows you to easily mock HTTP requests by providing you with the HttpTestingController service.
•Using the HttpClientTestingModule and HttpTestingController provided by Angular makes mocking out results and testing http requests simple by providing many useful methods for checking http requests and providing mock responses for each request.
•abstract class HttpTestingController {
• abstract match(match: string | RequestMatch | ((req: HttpRequest<any>) => boolean)): TestRequest[]
• abstract expectOne(url: string, description?: string): TestRequest
• abstract expectNone(url: string, description?: string): void
• abstract verify(opts?: { ignoreCancelled?: boolean; }): void
•}
•
•Match:- Search for requests that match the given parameter, without any expectations.
•ExpectOne: - Expect that a single request has been made which matches the given URL, and return its mock.
•ExpectNone:- Expect that no requests have been made which match the given URL.
•Verify :- Verify that no unmatched requests are outstanding.
Test Request
•Methods:-
•flush() :- Resolve the request by returning a body plus additional HTTP information (such as response headers) if provided. If the request specifies an expected body type, the body is converted into the requested type. Otherwise, the body is converted to JSON by default.
•error():- Resolve the request by returning an ErrorEvent (e.g. simulating a network failure).Resolve the request by returning an ErrorEvent (e.g. simulating a network failure).
•event() :- Deliver an arbitrary HttpEvent (such as a progress event) on the response stream for this request.
I welcome you all to this amazing course. Hope the learning would add value to your knowledge and you will learn How to write angular unit tests using Jasmine and Karma
Wishing you a happy understanding. Please do comment and provide feedback on the course.
Requirements
Visual Studio Code
Before continuing on this course we should have basic knowledge of Angular
This course will teach you about:
Angular unit test case using Jasmine and Karma, we will cover every topic which we use to create an angular application
Automated testing concepts and tools
What to unit test and how angular unit test flow
Tracking how much of your code is covered by tests using code coverage
Testing re-usable components
Testing templates driven
Testing forms driven
Testing Spy
Testing HTTP client
Testing navigation
Testing attribute directives
Mocking dependencies
Working with asynchronous operations
What is TestBad
The source code is also attached topic-wise.
This course is suitable for the following:
Beginner and experienced angular developers
About project implementation
In this course, we will see each topic with a real-time example and we will see how to implement all concepts in Visual studio code so we are able to understand it very well.
I recommend, please you install visual studio code so it will be helpful to implement logic in visual studio and you will learn every concept practically.
It will be very helpful if you have basic knowledge of angular.
I am glad that you successfully completed the course.
Hope you enjoyed it.
Keep growing.
Have a wonderful life ahead!!!!!