Error: Attempting to access the 'token' property of a null value is not permitted

One of the services I have returns all City data from a web service.

@Injectable()
export class CityService {
  constructor(private http: Http, private router: Router,
  private auth: AuthService) { }

  public getAllCity(): Observable<City[]> {
    let headers = new Headers();
    headers.append('x-access-token', this.auth.getCurrentUser().token);
    return this.http.get(Api.getUrl(Api.URLS.getAllCity), {
      headers: headers
    })
      .map((response: Response) => {
        let res = response.json();
        if (res.StatusCode === 1) {
          this.auth.logout();
        } else {
          return res.StatusDescription.map(city => {
            return new City(city);
          });
        }
      });
  }
}

In order to test this service, I attempted the following code. Now, I am looking for advice on how to effectively test the CityService.

describe('Service: City', () => {
    let service: CityService;

    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [],
            providers: [CityService, AuthService, Http, ConnectionBackend],  
            imports: [RouterTestingModule, HttpClientTestingModule, HttpModule] 
        });
    });

    beforeEach(() => {
        service = TestBed.get(CityService);
    });

    it('#getAllCity should return real value', () => {
        expect(service.getAllCity()).toBe('real value');
    });
});

While running this code, I encountered the following error:

TypeError: Cannot read property 'token' of null

Can you provide any examples or tutorials that can guide me on how to effectively test and display the city data in ng test?

This is my first attempt at testing, any suggestions or examples would be greatly appreciated.

Answer №1

If there is no current user, then it is possible to just return from the function.

if(!this.auth.getCurrentUser()){
    return;
}

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

Verify the length of an array within an object using JavaScript

I am facing a problem with an object. Here is what it looks like: const array = { "entities": [ { "annexes": [ { "buildingUniqueIds": [] }, { ...

Troubles with incorporating Ngb bootstrap into Angular due to dependency conflicts

As a newcomer to Angular, I am venturing into creating an image slider carousel in Angular using the ng-bootstrap component. After setting up my Angular project, I proceeded to install "ng bootstrap" within the project through npm install --save @ng-bootst ...

What benefits does importing bootstrap.scss into styles.scss provide compared to adding it directly to the styles block in .angular.cli.json?

What are the advantages of importing bootstrap.scss into the styles.scss file compared to adding it to the .angular-cli.json styles block? Which approach is better and why? styles.scss @import '~bootstrap/scss/bootstrap.scss'; vs .angular-cl ...

I am experiencing an issue where the mat-header-cell components are not appearing after navigating

After initially loading the page, mat-header-cell displays fine. However, upon navigating to a second page, refreshing it in the browser, and then returning to the original page, the mat-header-cell is no longer visible. It only reappears after manually re ...

The e2e directory seems to be missing from my Angular project

https://i.stack.imgur.com/xzrlb.png Despite reinstalling the CLI, the E2E feature still eludes me. ...

What is the best way to format a User object into JSON before sending it to an API endpoint?

Encountering an error 400 when attempting to submit a POST request. "$.User": [ "The JSON value could not be converted to WebApi.Models.User. Path: $.User | LineNumber: 5 | BytePositionInLine: 19." ] } Detailing my Order Model with ...

How can I assign two different colors based on the type in Typescript?

I am configuring a color property based on the nature of the display. colorStyle: { textAlign: "center", backgroundColor: "transparent", color: (theme.colors.BaseColor.Red as any).Red4, } The cu ...

Guide for referencing brackets with Joi validation

{ "visibleFields": { "design.content.buttons.action.type": { "SHOW_CLOSE": true, "URL": true, "CALL_PHONE": true }, "design.content.formFields": false, "success": fal ...

The object in an Angular 11 REACTIVE FORM may be null

I am looking to incorporate a reactive form validation system in my application, and I want to display error messages based on the specific error. However, I am encountering an error that says: object is possibly 'null'. signup.component.html &l ...

Ways to avoid using a specific type in TypeScript

Imagine having a class that wraps around a value like this: class Data<T> { constructor(public val: T){} set(newVal: T) { this.val = newVal; } } const a = new Data('hello'); a.set('world'); // typeof a --> Primitiv ...

Unable to set a breakpoint within Angular constructor or OnInit method

I am currently facing an issue with my Angular application where breakpoints set in F12 tools in Chrome or IE are not working. I have a simple test case below: export class LoginComponent implements OnInit { message: string; constructor(private r ...

The issue with importing fonts in CSS causing an error is encountered when utilizing an exported Angular library

I have a components library for Angular that relies on line-awesome icons. To include the necessary fonts and styles, I am using a CDN in the main SCSS file as shown below: @import url('https://fonts.googleapis.com/css2?family=Nunito:wght@200;300;400; ...

There seems to be a problem fetching the WordPress menus in TypeScript with React and Next

Recently I've started working on a project using React with TypeScript, but seems like I'm making some mistake. When trying to type the code, I encounter the error message: "TypeError: Cannot read property 'map' of undefined". import Re ...

Angular navigation did not work as expected

Created a basic webpage using Angular CLI version 8.3. The issue is as follows: For example: www.domainname.com is working fine. www.domainname.com/basicprinciples will work if visited through the main page, but it does not work when directly visiting w ...

Changing the ngModel value within ngFor loop

I am working on a project where I need to display a list of grades from an object called 'grades'. Additionally, I want to integrate a slider component for each grade, with the value of the slider corresponding to a predefined list. However, it s ...

Gradle synchronization in IntelliJ causing missing folders in WAR Artifact

Currently, I am working on a Spring MVC application that incorporates TypeScript. The TypeScript code is transpiled using a Gradle task from the directory src/main/ts to build/ts. Subsequently, the resulting JavaScript files are added to the WAR file usin ...

Challenges encountered while implementing Cognito API with Angular's HttpClient and HttpHeaders

Recently, I've been facing a dilemma between HttpClient and Axios. When I implement the following code: const requestBody = { grant_type: 'refresh_token', client_id: environment.APP_COGNITO_CLIENT_ID, refresh_token: thi ...

The process of building an Angular package results in the creation of if(false) {...}

I'm currently working on an Angular package repository hosted on GitHub at https://github.com/marcobuschini/parking-widget. All my tests pass successfully and there are no errors when I build using ng build. However, the resulting code contains some i ...

Is there any drawback in transforming Observables into promises?

There are situations where subscribing in a component is necessary instead of using an async pipe. In scenarios where only one value will be emitted by the observable, is there any drawback or downside to converting it to a promise? If we are not subscrib ...

Trouble with a third-party library component not functioning properly on the server side in a Next.js environment

I've encountered a puzzling issue lately in my work. Recently, I started using the new NextJS v13 with React server components. I'm integrating it into a project that depends on a small private third-party library I created and shared among mul ...