Login in particular react component using Jest and enzyme

I have to write the test case for this particular component as given below:-

import React from 'react';

import auth from 'containers/Login/authService';
class Footer extends React.Component {


    render() {

      if(!auth.loggedIn()){
        return (
          <div className="hidden">Not Logged In</div>
        );
      }else
        return (
            <footer>
                <span>XYZ</span>
            </footer>
        );
    }

}

export default Footer;

I have done the testing for Not Logged In part, but I am unable to test for the XYZ part. My test case file is as below:-

import React from 'react';
import { mount } from 'enzyme';
import Footer from '../Footer';
import { login } from '../../../containers/Login/authService';

describe('Footer mount testing', () => {
  const wrapper = mount(<Footer />);

  it('For not logged in user', () => {
    expect(wrapper.find('.hidden').length).toBeGreaterThan(0);
  });


  it('For logged in user', () => {
    jest.mock('../../../containers/Login/authService', () => ({
      login: true,
    }));
    login.mockImplementation(() => Promise.resolve('true'));
    expect(wrapper.text()).toEqual('XYZ');
  });
});

While running this I always get an error TypeError: Cannot read property 'mockImplementation' of undefined

I am not able to login in this particular module in order to check.

containers/Login/authService file as below:-

import request from 'utils/request';
import {config} from 'utils/config';
let localStorage;

// If we're testing, use a local storage polyfill
if (global.process && process.env.NODE_ENV === 'test') {
  localStorage = require('localStorage');
} else {
  // If not, use the browser one
  localStorage = global.window.localStorage;
}

let auth = {
  /**
   * Logs a user in, returning a promise with `true` when done
   * @param  {string} username The username of the user
   * @param  {string} password The password of the user
   */
  login (username, password) {
    if (auth.loggedIn()) return Promise.resolve(true);

var data ={username:username, password:password}
    console.log("#" + data + "#");

    let requestData = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        "Authorization": "Basic d2ViX2FwcDo="
      },
      body : JSON.stringify(data)
    };

    return request.post(config.serverHost+'/api/core/login', requestData)
      .then(response => {
        console.log('response received',response);
        // Save token to local storage
       // if(response.status == 200)
        localStorage.token = JSON.stringify(response);
        return Promise.resolve(response)
      })
  },

  logout () {

    return new Promise((resolve, reject) => {
      localStorage.removeItem('token');
      resolve(true)
    });

  },
  /**
   * Checks if a user is logged in
   */
  loggedIn () {
    return !!localStorage.token
  },

export default auth
728x90

1 Answers Login in particular react component using Jest and enzyme

mockImplementation cannot be used on login because it's not a function. It doesn't make sense to mock it in Footer test because the nearest unit to mock is loggedIn.

A proper unit test is:

jest.spyOn(auth, 'loggedIn').mockReturnValue(true);
const wrapper = mount(<Footer />);
expect(wrapper.text()).toEqual('XYZ');

The problem with this test suite is that tests are cross-contaminated. mount should be done in beforeEach, not in describe scope.

4 months ago