1

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

R. Richards
  • 24,603
  • 10
  • 64
  • 64
max
  • 39
  • 9

2 Answers2

0

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?

mbojko
  • 13,503
  • 1
  • 16
  • 26
  • Same here. I used localStorage for saving "user is logged in" and also some routes check this login (if not, redirecting to home-page) similar to cookie mechanism. When the "ng test" runs, pages for those routes are showing "Cannot read properties of null". – Gajen Dissanayake Jul 23 '22 at 02:18
0

If you are still looking for answer this worked for me . After creating your mock spy for other service add below block. this is the simplest mocking for localStorage

beforeEach(() => {
const localStorageMock = (() => {
  let store: { [key: string]: string } = {};

  return {
    getItem: (key: string) => store[key] || null,
    setItem: (key: string, value: string) => store[key] = value,
    removeItem: (key: string) => delete store[key],
    clear: () => store = {}
  };
})();

const localStorageSpy = spyOnProperty(window, 'localStorage', 'get').and.returnValue(localStorageMock);
localStorage.setItem('details', "hello details");
fixture = TestBed.createComponent(ExComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});

afterEach(() => {
// Remove the mock data from localStorage after the test is done
localStorage.removeItem('details');
});

after each block will allows you to modify details object for each of your test case

Ashok Ogirala
  • 121
  • 2
  • 15