Search code examples
javascriptnode.jsjestjsnodes

How to test a function with Jest that processes data from an external variable


I want to test a function that returns a user by ID from a list of users!! There is a file responsible for working with the list of users:

const users = [];
const getUser = (id) => users.find((user) => user.id == id);
module.exports = { users, addUser, removeUser, getUser, getUsers };

Unfortunately, I did not find a solution on how to test this function. Expected result is undefined, because the users array is empty. I do not understand how I can replace an array of users for testing.

const { getUser } = require('../users');

describe('Socket', () => {

  let socketId;

  beforeEach(() => {
    socketId = 'qwertyqwerty';
  })

  test('getUser', () => {
    const user = getUser(socketId);

    expect(user).toEqual({id: 'qwertyqwerty',user:{username: 'Max'}});
  });

})


Solution

  • Conjured a decision!!! in short. used a babel-plugin-rewire. And here's how to implemen: users.js

    import Helper from './Helper';
    
    const users = [];
    
    const user = {
      getUser: (id) => users.find((user) => user.id == id),
    }
    
    module.exports = user;

    And test file:

    const User = require('../users');
    
    User.__Rewire__('users', [{id:'qwertyqwerty',user:{username: 'Max'}},{id:'asdfghasdfgh',user:{username: 'Andy'}}]);
    
    describe('Socket', () => {
    
      let socketId;
    
      beforeEach(() => {
        socketId = 'qwertyqwerty';
      })
    
      test('getUser is user error', () => {
        const user = User.getUser(socketId);
        expect(user).toEqual({id: 'qwertyqwerty',user:{username: 'Max'}});
      });
    
    })

    Thanks to Always Learning, for the quick and correct answer )))