How to test if condition using jest

Hi,

I want to test the below mentioned function using jest and am not able to figure out how can I achieve full code coverage for this function.

For the sake of clarity I have created a function just similar to what I am using,

setName: function setName () {
        var storage = localStorage.getItem(user);
        var session = sessionStorage.getItem(temp);
      
        if ((session === null || session === undefined) && (storage === null && storage === undefined)) {
          var name = "window.name";
      
          if (name  === 'John') {
            changeName(name);
          } else if (name === 'Jane') {
            changeName(name);
          } else if (name  === 'Mark') {
            changeName(name);
          } else {
            changeName('John');
          }
        } else if (session !== null) {
          changeName(session);
        } else if (storage !== null) {
          changeName(storage);
        }
      }

Any help is appreciated

Session storage should be the same.

If you’re using create-react-app or similar, you can get this very easily: https://github.com/facebook/create-react-app/blob/ed5c48c81b2139b4414810e1efe917e04c96ee8d/packages/react-scripts/template/README.md#initializing-test-environment

Note Jest uses global not window for the global object within your test files.

In your test, you assert what the value is in your mock local storage initially, then run the function, and assert what it should be afterwards.

  1. If you start the mock with a non-null/undefined value, then the value after running your function should then be the same in both storages (I assume).
  2. If you start the mock with null/undefined, then the value after running the function (with different values for global.name) should be what you expect (eg if you set global.name = 'Foobar' and storages are both null/undefined, the storage should be "John" post-function execution).
  3. Repeat for all possible branches.

I’m only assuming changeName is supposed to update both storages. Also setting the window.name will likely break anything that relies on that browser API (which is not much afaics). Also imo you have far too many conditionals there, so you’re going to have to write loads of tests to cover each branch, and the John/Jane/Mark bit is needless repetition, this is a good use of testing to refactor because you’ll start to get bored with repeating yourself in the tests and lose track