How to write unit test case to check modal is defined or not

23 Views Asked by At

I need to write unit test cases where i need to check

  1. when i'm in particular page then only onclick sign-out i get confirmation modal pop up.
  2. when i'm in other pages other than particular page onclick sign-out it should call a function

JS code

import { ConfirmationModal } from '../form.js';

export class Auth {
  attachListeners() {
    // signout
    this.store.on('signout', async () => {
      const { pathname } = this.store.location;
      const pagepath = `${this.store.hrefRoot}/my-account/pagepath`;
      if (pathname === pagepath) {
        this.pagepathWarningModal(pathname);
      } else {
        this.onSignOutPage(pathname);
      }
    });
  }

  async onSignOutPage() {
    localStorage.removeItem('Hello World!');
  }

  async pagepathWarningModal(pathname) {
    const ph = {
      deleteShould: 'Delete changes',
      leave: 'Leave',
      cancel: 'Cancel',
    };
    const onConfirm = async () => {
      this.onSignOutPage(pathname);
    };

    try {
      await ConfirmationModal({
        onConfirm,
        title: ph.changesToQuickOrderWillNotBeSaved,
        confirmText: ph.leave,
        abortText: ph.cancel,
      });
    } catch (e) {}
  }

  async signout() {
    this.session = undefined;
    this.save();
  }
}

Unit test file


import { Auth } from '../../../scripts/modules/Auth.js';
import { Hello_world } from '../scripts.js';
/**
 * @param {Partial<Store>} [overrides]
 * @returns {Partial<Store>}
 */
const makeMockStore = (overrides = {}) => ({
  location: window.location,
  upstreamURL: 'http://localhost',
  ...overrides,
});

describe('Auth Script', () => {
  /** @type {Partial<Store>} */
  let mockStore;
  /** @type {Record<keyof Console, jest.Mock & { squelch: () => void }>} */
  let mockLogger;
  /** @type {(name: string) => typeof console} */
  let _ogLogger;
  /** @type {Auth} */
  let auth;
  describe('given localStorage', () => {
    beforeAll(() => {
      _ogLogger = { ...global.logger.getLogger('Auth') };
      localStorage.setItem(Hello_world, []);
    });

    beforeEach(async () => {
      mockStore = makeMockStore({
        Auth: {
          session: {
            customer: {
              email: '[email protected]',
            },
          },
        },
        isReady: () => true,
        on: jest.fn().mockImplementation((ev, action) => {
          if (ev === 'auth:signout:submit') action();
        }),
        emit: async () => {},
        load: async () => {},
        DataLayer: { pageShownHandler: jest.fn(() => true) },
      });

      // wrap each logger function
      mockLogger = global.logger.getLogger('Auth');
      Object.entries(_ogLogger).forEach(([lvl, fn]) => {
        const newFn = jest.fn().mockImplementation(fn);
        newFn.squelch = () => {
          newFn.mockImplementation(() => {});
        };
        mockLogger[lvl] = newFn;
      });

      auth = new Auth(mockStore);
    });

    afterEach(() => {
      Object.keys(_ogLogger).forEach(lvl => {
        mockLogger[lvl] = _ogLogger[lvl];
      });
    });

    describe('when there is order pad skus key in the local storage', () => {
      test('then user clicks on signout', async () => {
        auth.store.emit('signout');
        const Hello_worldVar= JSON.parse(localStorage.getItem(Hello_world));
        expect(Hello_worldVar).toBeNull();
      });
    });
  });
});

How to write unit test so that when i'm particular page the modal displays in all other pages no modal displays signout directly

0

There are 0 best solutions below