jest test – TypeError: Cannot read property 'filter' of null

I’m quite new with jest testing and I’m having trouble to understand how Jest deals with the functions I’m trying to test. Here’s my problem:

I’m trying to test the following, quite simple function, which will receive a bookId and will find the object within an array that containa such id. All is vanilla js, no react.

function catchSelectedBook(bookId) {
  const objectSearchAsString = localStorage.getItem('objecttransfer');
  const booksObject = JSON.parse(objectSearchAsString);
  const currentBook = booksObject.filter((book) => book.id === bookId);

  return currentBook;
}

The unit test Jest code is the following:

describe('Given a function that is given as argument the id', () => {
  test('When invoked, it finds the book that matches such id', () => {

   const returnMokObject = {
      kind: 'books#volumes',
      totalItems: 1080,
      items: [
        {
          kind: 'books#volume',
          id: 'HN1dzQEACAAJ',
        }],
    };
   mockLocalstorageJest();
   const answer = catchSelectedBook('HN1dzQEACAAJ');
    expect(answer.id).toBe('HN1dzQEACAAJ');
  });
});

The function mockLocalstorageJest sends to the local storage an object so that it can be get when the function catchSelectedBook is tested
I export my function like this:

module.exports = {
  catchSelectedBook,mockLocalstorageJest,
};

And I import the function into the test file like this:

const { catchSelectedBook, mockLocalstorageJest} = require('./book-details.js');

Whenever I run the test, I got the following error message:
enter image description here

Does that mean that Jest doesn’t have the array method "filter" defined?

Thanks!

119 thoughts on “jest test – TypeError: Cannot read property 'filter' of null”

  1. With havin so much content and articles do you ever run into
    any issues of plagorism or copyright infringement? My blog has a
    lot of completely unique content I’ve either created myself or outsourced
    but it looks like a lot of it is popping it up all over the
    internet without my permission. Do you know any
    methods to help prevent content from being ripped off? I’d certainly appreciate it. https://buszcentrum.com/priligy.htm

    Reply
  2. I just like the helpful info you provide to your articles.
    I will bookmark your weblog and test once more here frequently.

    I’m rather sure I will be informed lots of new stuff right
    right here! Best of luck for the following!

    Reply
  3. Pingback: ivermectin 875
  4. Pingback: nelpa deltasone
  5. Pingback: ivermectin cost
  6. Pingback: sildenafil 100mg
  7. Pingback: otc viagra

Leave a Comment