Angular Component Test Results in TypeError Error Failure

After defining a custom error class called CustomError:

export class CustomError extends Error {
    constructor(message?: string) {
        super(message);
        Object.setPrototypeOf(this, CustomError.prototype);
    }
}

I want to throw instances of CustomError from an Angular component:

@Component({
    moduleId: 'module.id',
    templateUrl: 'my.component.html'
})
export class MyComponent {
    someMethod(): void {
        throw new CustomError();
    }
}

To test if CustomError is thrown, I have created the following test:

describe('MyComponent', () => {

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [MyComponent]
        }).compileComponents();
    }));

    beforeEach(async(() => {
        fixture = TestBed.createComponent(MyComponent);
        component = fixture.componentInstance;
    }));

    it('throws CustomError', () => {
        expect(component.someMethod).toThrowError(CustomError);
    });
});

The above test passes successfully. But when I add a property named someProperty to MyComponent like this:

@Component({
    moduleId: 'module.id',
    templateUrl: 'my.component.html'
})
export class MyComponent {
    someProperty: string  = "Why does this break it?";

    someMethod(): void {
        console.log(this.someProperty);  // This breaks it, why?
        throw new CustomError();
    }
}

And try to use that property within the function under test (in this case trying to write to the console), my test fails with a TypeError:

Expected function to throw AuthError, but it threw TypeError.
        at Object.<anonymous> (webpack:///src/app/auth/login/login.component.spec.ts:46:32 <- config/karma-test-shim.js:68955:33) [ProxyZone]
        ...

This unexpected TypeError and failure in the test occurs when processing the introduced someProperty. The issue seems to be related to how someProperty is handled within the component's function.

Answer №1

You seem to have lost track of the context at this.

getJasmineRequireObj().toThrowError = function(j$) {
  function toThrowError () {
    return {
      compare: function(actual) {
        var threw = false,
          pass = {pass: true},
          fail = {pass: false},
          thrown;

        if (typeof actual != 'function') {
          throw new Error('The actual value is not a Function');
        }

        var errorMatcher = getMatcher.apply(null, arguments);

        try {
          actual(); // call the referenced function component.someMethod

I suggest writing it like this:

expect(component.someMethod.bind(component)).toThrowError(CustomError);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Optimal Angular Project Structure for Creating an App with Admin Backend

After finishing "ng-book: The complete book on Angular 6," I am diving into Angular as a newcomer. As I venture into building my application, I have a specific question that has been lingering in my mind. The vision for my project includes: MainLayout: ...

Ways to resolve the issue of npm being unable to globally install typescript

While trying to globally install TypeScript using npm sudo npm install -g typescript An error occurs during the installation process with the following message: ENOENT: no such file or directory, chmod '/usr/local/lib/node_modules/typescript/bin/ ...

When using Sequelize, you may notice that extra spaces are automatically added at the end of the DataTypes.CHAR data type

Here is an example of how I structure my Store.ts file: import {DataTypes, Model, ModelAttributes} from "sequelize"; export default class Store extends Model { declare id: number declare name: string declare phone: string } export const S ...

Encountering a promise error when using TypeScript and React Lazy

I've been working with React and TypeScript, incorporating a higher order component to verify user authentication. However, after implementing the hoc, I encountered an error in my routes: /home/nidhin/Documents/Nidhinbackup/F/iot-remsys-demotwo/rem ...

Managing a MySQL database in NodeJS using Typescript through a DatabaseController

I'm currently working on a restAPI using nodejs, express, and mysql. My starting point is the app.js file. Within the app.js, I set up the UserController: const router: express.Router = express.Router(); new UserController(router); The UserControll ...

Is there a way to recursively convert property types from one to another in an object that contains optional properties?

The scenario: I am currently working with MongoDB and a REST API that communicates using JSON. MongoDB uses objects instead of identifiers for documents, but when these objects are stringified (such as in a response body), they get converted into strings. ...

Angular 4: Automatically dismiss modal once form submission process is complete

My Bootstrap 4 modal closes properly when I press the close button. However, I want the modal to close after submitting the create button in the form. I am using Angular 4. <div class="modal fade" id="createLabel" tabindex="-1" role="dialog" aria-label ...

Is there a way to implement imports based on a specific condition?

I'm just starting to learn Angular and TypeScript. My goal is to redirect multiple hostnames to a single Angular 6 project because most aspects are the same, with only language and URLs varying. For example, here's what I have implemented in ap ...

Managing nested request bodies in NestJS for POST operations

A client submits the following data to a REST endpoint: { "name":"Harry potter", "address":{ "street":"ABC Street", "pincode":"123", "geo":{ &q ...

You can't access the values from one subscribe in Angular 2 within another subscribe (observable) block

Is there a way to properly handle the values from the subscribe method? I am facing an issue where I want to use this.internships in another subscribe method but it keeps returning undefined. Your assistance is greatly appreciated! Code: ngOnInit(): voi ...

The Azure DevOps pipeline is indicating that the global CLI version is higher than the local version you have on

I'm currently facing an issue while trying to deploy an Angular front end to Azure pipeline from GitHub using yaml. The problem occurs during the npm build and install stage, with an error message stating 'Your global Angular CLI version (15.2.6) ...

Adjust the column width in Angular material tables

Is it possible to adjust the width of individual columns? I've attempted various methods, but it appears that the columns are consistently equal in width regardless of any styles applied. ...

Tips for maintaining consistent column width when scrolling down (column juggling) within a table in your Angular application

Take a look at this preview of the app I'm currently developing. https://stackblitz.com/edit/angular-ivy-3mrzkr In order to handle the large amount of data in my real app, I needed to incorporate a third-party scrolling module. After testing out cdk ...

What could be causing my AngularJS controller to fail in my jasmine test?

I encountered the following error message: "Controller: MainCtrl should retrieve a list of users and assign to scope.users FAILED TypeError: 'undefined' is not a function (evaluating 'Users.findAll()') at /Users/John/NetBea ...

Utilizing event bubbling in Angular: a comprehensive guide

When using Jquery, a single event listener was added to the <ul> element in order to listen for events on the current li by utilizing event bubbling. <ul> <li>a</li> <li>b</li> <li>c</li> <li>d< ...

The Magic of Jasmine's toMatch Method and the Power of Parentheses

Have you observed that when using Jasmine Expect with toMatch, it fails if the string being matched contains a (? If so, what steps did you take to address this issue? For example: This statement fails or returns "False" instead of "True": expect("test ...

Testing the object created by a factory with unit tests

I am currently working on writing a unit test for a Factory class, but when I run the test with PHPUnit, it throws a fatal error regarding the creation of the Product. Fatal error: Class 'JsonStorage' not found Directory Structure -\ ...

Increasing response buffer size in Node.js fetch for version 2.x.x

Currently in the process of implementing an API request using nodejs-fetch and I've encountered an issue. The documentation states that the maximum buffer size for fetch is 16kB, but the response I need to retrieve is 53 kB. This causes the .fetch() f ...

Utilizing nested objects in ngrx/store effects

Currently, I am in the process of learning Angular 2 and experimenting with ngrx/store. However, I am encountering some challenges when it comes to dealing with certain special cases. For instance, one issue I am facing is attempting to remove a parent ob ...

Angular Unit Testing: Executing Multiple expectGET's within a Singular Test

I am facing an issue with a unit test that fails to read the JSON in the second request properly This is my implementation of the Config factory (function() { 'use strict'; angular.module('commercial.factories').factory(&apos ...