How to test if condition using jest


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 = "";
          if (name  === 'John') {
          } else if (name === 'Jane') {
          } else if (name  === 'Mark') {
          } else {
        } else if (session !== null) {
        } else if (storage !== null) {

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:

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 should be what you expect (eg if you set = '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 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