Need help writing tests for /api/src/lib/auth.js

I thought I would try and write some tests for api/src/lib/auth.js and getCurrentUser went well enough, but I’m having some trouble with hasRole. hasRole makes a call to isAuthenticated which requires context which seems to be a global variable. I think it should be as simple as

it('should check roles', function testRoles() {
  // set context somehow
  const hasSomeRole = hasRole('some-role')

  expect(hasSomeRole).toBeTruthy();
});

Here is how I’ve tried to set the context without any luck

context.currrentUser = 'foo';

global.context.currentUser = 'foo';

Object.defineProperty(context, 'currentUser', {
  value: 'foo'
}); 

jest.spyOn(context, 'currentUser').mockReturnValue('foo');

Any idea how I could test hasRole?

Hi @LarkSoftware does the section on mocking authentication and roles here help?

Thank you so much @dthyresson . Somehow I missed that documenation. Here is what I added to get my test to work:

it('should check roles', function testRoles() {
  mockCurrentUser({ name: 'test-user', roles: ['some-role'] }); // I added this line
  const hasSomeRole = hasRole('some-role')

  expect(hasSomeRole).toBeTruthy();
});
2 Likes