jasmine testing against localstorage with angular

Viewed 45

I'm trying to wrap my head around why my test is failing. When the page loads a value is grab from the localstorage in the constructor and after a method sortItems is called

  constructor(private loadingCtrl: LoadingController) {

                this.details = JSON.parse(localStorage.getItem('details'));

                this.sortItems('id')

              }

  sortItems(value) {
    if (value === 'id') {
      this.details.items = this.details.items.sort((a, b) =>
      a.id > b.id ? 1 : b.id > a.id ? -1 : 0
    );
   }

   if (value === 'name') {
    this.details.items = this.details.items.sort((a, b) =>
    a.name > b.name ? 1 : b.name > a.name ? -1 : 0
  );

 }
  }

my jasmine test case has this below

  it('should create', () => {
    component.details = order;
    expect(component).toBeTruthy();
  });

where i have a mock data in a file

const order = {
        first_name: 'Michele T',
        id: 41861,
        items: [{
            id: 135878,
            name: 'Arden',
            status: 'active'
        }],
    };

const mockLocationArray = [order];

export { order, mockLocationArray };

when i run ng test i get an error Cannot read properties of null (reading 'items') but items is already defined in the test case

1 Answers

When the page loads a value is grab from the localstorage in the constructor and after a method sortItems is called

I'm guessing the component is created (or actually not created, because it fails) in your beforeEach(), sth like fixture = TestBed.createComponent(MyComponent). It's trying to create the component, the constructor runs, tries to access details from localStorage, finds nothing, sortItems tries to sort undefined, and you get an error. It's all happening even before your 'should create' runs.

One solution would be to mock localStorage, and do that before creating the component. Here's a thread about mocking localStorage in Jasmine: How to mock localStorage in JavaScript unit tests?

Related