0

I need to test different use cases in my component, when the user is logged in, and when the user is not logged in, I can start with one state, but then I can't move to the other.

Right now, I start with not logged in state, after that I wrote a test case to test logged in state, I'm trying to mock jwt-decode library at that point before the render but it's not doing the mock.

Is there another way to change mock implementation? or is it related to jwt-decode?

So far, I tried this answer, but it didn't work.

The important lines to read are

      (mockedJwtDecode as any).mockImplementationOnce(() => () => ({
        id: 222,
        exp: new Date().getTime()
      }));

and here's the full code

import React from 'react';
import '@testing-library/jest-dom/extend-expect'
import { defineFeature, loadFeature } from 'jest-cucumber'
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { fakeForum, } from '../../../components/src/fake-data-generator/forum';
import TestContextWrapper from '../../../components/src/TestContextWrapper.web';
import { ForumCardContainer } from '../src/forum-card-container';

import * as mockedJwtDecode from 'jwt-decode';


const feature = loadFeature('./__tests__/features/forum-card-container.feature');


localStorage.setItem('token', 'anytoken');

jest.mock('jwt-decode', () => jest.fn(() => ({ id: 0, exp: 0 })));


const user = userEvent.setup();

defineFeature(feature, (test) => {

  test('...', () => {
    ...
  });

  test('like/dislike buttons should allow requests to be sent if logged in', ({ given, when, then }) => {

    const commentHandler = jest.fn();
    const onAnonymousInteraction = jest.fn();

    given('forum card container is rendered', () => {

      // not working too
      // jest.mock('jwt-decode', () => jest.fn(() => ({ id: 222, exp: 2222222222 })));

      (mockedJwtDecode as any).mockImplementationOnce(() => () => ({
        id: 222,
        exp: new Date().getTime()
      }));

      render(
        <TestContextWrapper path="">
          <ForumCardContainer
            forum={fakeForum}
            singlePageMode={false}
            commentHandler={commentHandler}
            onAnonymousInteraction={onAnonymousInteraction}
          />
        </TestContextWrapper>
      );

    });
    when('user is logged in', () => { });
    then('user can cause a like/dislike requests when the buttons are clicked', async () => {

      const likeBtn = screen.getByRole('button', { name: 'like' });
      expect(likeBtn).toBeInTheDocument();
      await user.click(likeBtn);
      //expect(onAnonymousInteraction).not.toBeCalled();
    });
  });

});

Louay Al-osh
  • 3,177
  • 15
  • 28

0 Answers0