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

Tips for incorporating a captcha image into your angular 8 application

I would like to implement a captcha element with an image of letters and an input field for the user, (I prefer not to use the "I am not a robot" version) similar to this example: https://i.sstatic.net/dd1Gb.png Is this feature still available today? ...

Ionic 2 - Error: Module ""."" not found at runtime

Encountered a perplexing error while running my Ionic 2 application on localhost using the command: ionic serve I've diligently inspected all my imports for any incorrect paths in my TypeScript files, but haven't found anything amiss. The only ...

Looking to resolve a module-specific error in Angular that has not been identified

While practicing Angular, I encountered an error during compilation: Module not found: Error: Can't resolve './app.component.css' in 'D:\hello-world-app\src\app' i 「wdm」: Failed to compile. This is my app.compo ...

Backend is currently unable to process the request

Whenever a user clicks on a note in my notes page, a request is supposed to be made to the backend to check if the user is the owner of that particular note. However, for some reason, the request is not being processed at all. The frontend is built using ...

Having Trouble Displaying Data in HTML After Making a Get Request

Upon initialization, I retrieve the data using ngOnInit() ngOnInit(): void { this.http.get<any>(this.ROOT_URL + this.cookieService.get('cookie-name')).subscribe( function(res) { this.tableData = res.atVendor; co ...

Tips for removing the splash screen in Ionic 2

I've made changes to the config.xml file by setting the value of the splash screen to none. As a result, the splash screen no longer appears. However, I'm now encountering a white screen instead. Is there a way to prevent this white screen from a ...

In Typescript, convert an object into a different type while maintaining its keys in the resulting type

Imagine you have a code snippet like this type ResourceDecorator = (input: UserResourceDefinition) => DecoratedResourceDefinition const decorate: ResourceDecorator = ... const resources = decorate({ Book1: { resourceName: 'my-book', ...

The Mat-Timepicker is not visible after building in --prod mode

I have implemented mat-timepicker v5.1.5 successfully on my local environment. However, after building the app for production and deploying it on Tomcat server, the timepicker fails to display. No errors are shown during the build --prod command or in the ...

What is the process of extending a class in TypeScript?

I have a few services that contain the same code: constructor (private http: Http) { //use XHR object let _build = (<any> http)._backend._browserXHR.build; (<any> http)._backend._browserXHR.build = () => { let _xhr = _ ...

Issue TS1259: The module "".../node_modules/@types/bn.js/index"" can only be imported as the default using the 'esModuleInterop' flag

Currently, I am utilizing Hiro Stack.js which I obtained from the following link: https://github.com/hirosystems/stacks.js/tree/master/packages/transaction. For additional information, please refer to . Even when attempting to compile a fully commented out ...

Is Redux or Flux the default state management tool used in React?

After using npx create-react-app my-app --template typescript to create a new React app, what is the default software architecture (MVC, Redux, or Flux)? I've been researching the differences between them and it has left me feeling a bit confused. I w ...

An unexpected error has occurred: Uncaught promise rejection with the following message: Assertion error detected - The type provided is not a ComponentType and does not contain the 'ɵcmp' property

I encountered an issue in my Angular app where a link was directing to an external URL. When clicking on that link, I received the following error message in the console: ERROR Error: Uncaught (in promise): Error: ASSERTION ERROR: Type passed in is not Co ...

What is the best way to recycle a variable in TypeScript?

I am trying to utilize my variable children for various scenarios: var children = []; if (folderPath == '/') { var children = rootFolder; } else { var children = folder.childs; } However, I keep receiving the following error message ...

The library "vue-property-decorator" (v10.X) is causing issues with resolving in Webpack despite being successfully installed

Encountered an error message Module not found: Error: Can't resolve './decorators/Emit' while attempting to import functionality from the library vue-property-decorator. The package is installed and accessible, ruling out a simple installati ...

What is the sequence in which Jest executes its tests?

A fascinating challenge I've taken on involves testing a card game created in JavaScript using Jest. Currently, I have developed two tests: one to verify the creation of a 52-card deck and another to confirm that the player is dealt two cards at the ...

Activating the loader dismiss command will transition the swiper to the current page

Having a swiper and loader makes the scenario very straightforward. The loader is initialized whenever calculations are performed, and after successfully obtaining the result, the loader turns off and swipes to the second slide. <swiper-container #sl ...

A guide on transitioning from using require imports to implementing ES6 imports with the concept of currying

Currently in the process of migrating a Node/Express server to TypeScript. I have been using currying to minimize import statements, but now want to switch to ES6 import syntax. How can I translate these imports to ES6? const app = require("express")(); ...

When the state changes, the dialogue triggers an animation

Currently, I am utilizing Redux along with material-ui in my project. I have been experimenting with running a Dialog featuring <Slide direction="up"/> animation by leveraging the attribute called TransitionComponent. The state value emai ...

Tips for extracting key values from an array of objects in Typescript

I am working with an array called studyTypes: const studyTypes = [ { value: "ENG", label: "ENG-RU", }, { value: "RU", label: "RU-ENG", }, ]; Additionally, I have a state variable set ...

loop through an intricate JSON schema using Angular 5

I've been trying to figure out how to iterate a complex JSON in Angular 5. I came across the pipe concept, but it doesn't seem to work with JSON data like the one below. I'm trying to create an expandable table using this type of data, but I ...