8

I'm trying to test a few components that are using MSAL for authentication.

Thus far, I have a simple test, which test if my component can render, as follows:

let container;
beforeEach(() => {
    container = render(<NavBar/>)
});
test('Component renders', () => {
    expect(container).not.toBeNull()
})

When I run the test, I'm getting the following error:

BrowserAuthError: crypto_nonexistent: The crypto object or function is not available. Detail:Browser crypto or msCrypto object not available.
  
  at BrowserAuthError.AuthError [as constructor] (node_modules/@azure/msal-browser/dist/index.cjs.js:545:24)
  at new BrowserAuthError (node_modules/@azure/msal-browser/dist/index.cjs.js:7096:28)
  at Function.Object.<anonymous>.BrowserAuthError.createCryptoNotAvailableError (node_modules/@azure/msal-browser/dist/index.cjs.js:7113:16)
  at new BrowserCrypto (node_modules/@azure/msal-browser/dist/index.cjs.js:7413:36)
  at new CryptoOps (node_modules/@azure/msal-browser/dist/index.cjs.js:7782:30)
  at PublicClientApplication.ClientApplication (node_modules/@azure/msal-browser/dist/index.cjs.js:10027:58)
  at new PublicClientApplication (node_modules/@azure/msal-browser/dist/index.cjs.js:11307:23)

I'm unsure what the above means, but as far as I can understand, this error is occurring because the session is not authenticated.

My question can therefore be divided into the following:

  • What does this error mean?
  • How can I solve this error? (Can we bypass MSAL by any chance for testing purposes?)
Jeppe Christensen
  • 1,680
  • 2
  • 21
  • 50

1 Answers1

4

So basically, I've found that my <NavBar/> component were dependent on two MS Graph API calls namely getAccountData() and setAccountData(), which obviously needed a token to function, and caused the nasty error above.

Therefore, I decided to bypass the two functions by simply mocking them, like so:

jest.mock('../msGraph', () => ({ setAccountData: jest.fn() }))
jest.mock('../msGraph', () => ({ getAccountData: jest.fn() }))

I was not dependent on getting data from Graph in order to carry out my test - So the two mock functions does not return any data. (I could however have done so by adding it inside the brackets of jest.fn())

Jeppe Christensen
  • 1,680
  • 2
  • 21
  • 50
  • Thanks for this answer. Some guys have told update the `jest.config.js` file adding `globals: { crypto: require("crypto") }` , but it didn't work for me. – Sanka Sanjeewa Aug 04 '22 at 14:25