Search code examples
angularunit-testingkarma-jasmine

UNIT TEST ANGULAR ---> TypeError: Cannot read properties of null (reading 'name')


I'm having a problem creating the test file for the post-detail component. I always get this error:

image of error

Here is my post-detail.component.ts file:

post-detail.component.ts

Here is my post-detail.component.spec.ts file:

post-detail.component.spec.ts

could you help me to solve this problem?


Solution

  • You're trying to read the name property of undefined (in the PostDetailComponent, code row 24, name: this.user.name), because when you declare your component, the field user is not defined. That's why it tries to read the name field of the user object. You have a few ways to fix it:

    1. Add the optional chaining operator to the reading of the name property. You will have the next code on the 24th row: name: this.user?.name,.
    2. You can mock the user object in your tests. In the spec file on the 34th row mock the class field: component.user = {} as User;. Then when your component tries to read the name property, you will have an empty object, but not undefined and you will have no errors.