Udemy
    •  
    •  
    •  
    •  
    •  
    •  
    •  
    •  
Turn what you know into an opportunity and reach millions around the world.
Learn More
Your cart is empty.
Keep shopping
Angular unit test case with Jasmine & Karma
Rating: 4.0 out of 5(151 ratings)
731 students

Angular unit test case with Jasmine & Karma

Learn how to write Angular unit test case with Jasmine & Karma
Last updated 11/2022
English
English [Auto],

What you'll learn

  • Writing Angular unit test case with Jasmine & Karma
  • Understanding on Jasmin and Karma
  • Understanding on spy in angular
  • Writing Angular unit test case with Jasmine & Karma in All version of angular
  • The source code is also attached topic-wise.

Course content

1 section44 lectures6h 32m total length
  • Introduction1:32
  • Introduction of Jasmine & Karma7:01

    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.

  • How Angular Unit test case Flow8:24

    •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.

  • How to run angular unit test cases12:17

    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.

  • Jasmine & Karma Configuration With Angular10:08

    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.

  • First Angular Unit test case9:40
  • Exclude Angular unit test case from Execution5:13

    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.

  • Jasmin Matchers in angular unit test case3:41

    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().

  • ToBe and ToEqual in-built matcher in angular unit test4:43

    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.

  • toBe(true), toBeTrue() and toBeTruthy() , toBeFalse() and toBeFalsy() Jamine8:48

    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.

  • toBeGreaterThan() ,toBeGreaterThanOrEqual() ,toBeLessThan() ,toBeLessThanOrEqual4:32

    Demonstrate using Jasmine matchers toBeGreaterThan, toBeGreaterThanOrEqual, toBeLessThan, and toBeLessThanOrEqual in Angular unit tests with Jasmine and Karma.

  • toMatch() and toBeCloseTo() Jasmin Matcher4:26

    Explore how to use toMatch and toBeCloseTo in Jasmine for Angular unit tests, demonstrating regex matching and numeric precision checks with examples.

  • toBeDefined and toBeUndefined Jasmine matcher5:52

    Learn how toBeDefined and toBeUndefined in Jasmine help verify whether objects, variables, and functions are initialized in Angular unit tests.

  • tobenull() ,tocontain() ,tobeNan() , toBePositiveInfinity, toBeNegetiveInfinity6:13

    Learn how to use Jasmine matchers such as toBeNull, toContain, toBeNaN, and toBePositiveInfinity and toBeNegativeInfinity to handle null, undefined, and infinity scenarios in tests.

  • BeforeEach and AfterEach Jasmine functions11:08
  • BeforeAll and AfterAll in Jasmin Method2:51

    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.

  • Arrange-Act-Assert(AAA) Pattern4:38

    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.

  • TestBed and Component Fixture9:32

    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.

  • SpyOn to mock and Stub methods in angular unit test16:59

    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.

  • Change detection in angular unit test7:13
  • Debug Element & DOM events in angular unit test11:02

    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.

  • Call Private Method and private variable in angular unit test5:22
  • SpyOn Private Method in angular unit test3:33

    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.

  • Angular Unit test on interpolation10:32
  • Unit test on property binding6:15

    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.

  • Unit test on ngClass and ngStyle Binding9:06

    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.

  • Unit test on Attribute Binding10:28

    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.

  • Unit test on event Binding11:41

    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.

  • WhenStable, Async Test and twoWay data binding unit test16:53
  • FakeAsync and async in unit test5:42
  • Unit Testing on Conditional Rendering (If condition)7:11
  • Angular Unit test on ngSwitch7:02

    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.

  • Angular unit test on ngFor13:54

    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.

  • Angular unit test case on dependency injection12:31

    •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

  • Angular unit test case on Pipe and Custom Pipe12:00

    •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

  • Angular Unit test case on input output directive13:05
  • Angular unit test On Routing9:08

    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.

  • Angular Unit test case on lazy loading9:50

    •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'); }));

  • Angular Unit test case on Http Client or services method12:23

    •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.

  • Angular Unit test case for Subscribe method7:29
  • CreateSpy , createSpyObj and spyOn in angular unit test10:43
  • Angular unit test case on Reactive Forms11:56
  • Angular Unit test case on template driven form8:38
  • Code Coverage in angular unit test9:26

Requirements

  • Basic knowledge on Angular

Description

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!!!!!

Who this course is for:

  • developer
  • student
  • Angular developer