Jest: Test a function with a function inside

How can I test this function?

const userLoggedIn = () => {
  const token = store('Token')
  return token && token.split(':')[0]
}

I been trying with this, but I can’t find a way to pass ‘Token’ inside userLoggedIn():

describe('', () => {
  it('', () => {
    const store = jest.fn();
    store.mockReturnValueOnce("1234:567:890")
    expect(userLoggedIn()).toMatch()
  })
})

Assuming you imported store in like this:

import store from './store';

export const userLoggedIn = () => {
  const token = store('Token');
  return token && token.split(':')[0];
};

the test file should be:

import { userLoggedIn } from './login';

import store from './store';

jest.mock('./store', () => ({
  __esModule: true,
  default: jest.fn(),
}));

describe('', () => {
  it('', () => {
    store.mockReturnValueOnce('1234:567:890');
    expect(userLoggedIn()).toMatch('1234');
  });
});
1 Like

Almos!

import userLoggedIn from '../helpers/authorisation'

jest.mock('store2', () => {
  const mockStore = jest.fn()
  mockStore.mockReturnValue('768:423:999')
  return mockStore
})

describe('When user request to be log in', () => {
  it('Should return first part (:) of the Token', () => {
    expect(userLoggedIn()).toBe('768')
  })
})