0

I was trying to build a test on a method of my controller, and when I tried to throw a customer exception that I created to use when the app don't find the user, I got this error: AssertionError [ERR_ASSERTION]: Local storage does not seem to have been initialized or in context, please make sure you use local storage middleware.

Edit: I tried to mock local storage, but i got the same error.

The test:

import { cpfValidator } from '../src/v1/helpers/validators';
import { ResourceNotFoundException } from "../src/v1/exception/error-exception";

describe('Testar as rotas', () => {
    it('Informar todos os produtios relacionados a um usuário', async () => {
      const resposta = cpfValidator('CPF38751468831', '')
      expect(resposta).toThrow(TypeError);
    }, 120000);
  });

The cpf validator

export async function cpfValidator(userId: string, xTokenInfo?: string): Promise<string> {
  if (userId !== 'me' && new RegExp(/^CPF[0-9]{11}$/).test(userId) && cpf.isValid(userId))
    return userId.substr(3);
  else if (userId === 'me' && new RegExp(/^sub:CPF[0-9]{11}$/).test(xTokenInfo) && cpf.isValid(xTokenInfo.substr(4)))
    return xTokenInfo.substr(7);
  else {
    const logger = new Logger();

    logger.error('Erro ao validar documento. Número de CPF Inválido.', { "user-id": userId });

    throw new ResourceNotFoundException();
  }
}

The class of error:

export class ResourceNotFoundException extends GenericException {
    constructor() {
// consider ERRORS as a constant
        super(ERRORS[404].CODE, ERRORS[404].MESSAGE, ERRORS[404].HTTP_CODE);
    }
}

The class extended

import { HttpException } from '@nestjs/common';
export declare class GenericException extends HttpException {
    constructor(code?: string, message?: string, statusCode?: number);
}

PS: This was my first question and I'm new with Jest, so sorry for my mistakes.

  • Does this answer your question? [How to mock localStorage in JavaScript unit tests?](https://stackoverflow.com/questions/11485420/how-to-mock-localstorage-in-javascript-unit-tests) – Dvid Silva Mar 03 '20 at 18:50
  • I changed the test environment to jsdom and tried this, but i got the same error – Igor Tomaz Mar 05 '20 at 11:15

1 Answers1

0

You have to mock localStorage before the tests run, you can do so like this:

//browserMocks.js
var localStorageMock = (function() {
    var store = {};

    return {
        getItem: function(key) {
            return store[key] || null;
        },
        setItem: function(key, value) {
            store[key] = value.toString();
        },
        clear: function() {
            store = {};
        }
    };

})();

Object.defineProperty(window, 'localStorage', {
    value: localStorageMock
});

And in the jest config: "setupFiles":["browserMocks.js"]

As found, https://github.com/facebook/jest/issues/2098

Dvid Silva
  • 1,110
  • 13
  • 25
  • Thanks for your answer, I created the browserMocks.js, put the "testEnvironment": "jsdom" configuration on jest section in package.json and used "setupFiles": [ "./browserMocks.js" ] and I got the same error. – Igor Tomaz Mar 03 '20 at 20:15