React jest 和 MSAL 获取 BrowserAuthError :加密

vid*_*sha 8 java typescript reactjs jestjs package.json

我正在尝试测试一些使用 MSAL 进行身份验证的组件。

到目前为止,我有一个简单的测试,测试我的组件是否可以渲染,如下所示:

// <MsalInstanceSnippet>
const msalInstance = new PublicClientApplication({
  auth: {
    clientId: config.appId,
    redirectUri: config.redirectUri
  },
  cache: {
    cacheLocation: 'sessionStorage',
    storeAuthStateInCookie: true
  }
});
Run Code Online (Sandbox Code Playgroud)

当我运行测试时,我收到以下错误:

 BrowserAuthError: crypto_nonexistent: The crypto object or function is not available. Detail:Browser crypto or msCrypto object not available.

      10 |
      11 | // <MsalInstanceSnippet>
    > 12 | const msalInstance = new PublicClientApplication({
         |                      ^
      13 |   auth: {
      14 |     clientId: config.appId,
      15 |     redirectUri: config.redirectUri

      at BrowserAuthError.AuthError [as constructor] (node_modules/@azure/msal-common/dist/error/AuthError.js:27:24)
      at new BrowserAuthError (node_modules/@azure/msal-browser/src/error/BrowserAuthError.ts:152:9)
      at Function.Object.<anonymous>.BrowserAuthError.createCryptoNotAvailableError (node_modules/@azure/msal-browser/src/error/BrowserAuthError.ts:172:16)
      at new BrowserCrypto (node_modules/@azure/msal-browser/src/crypto/BrowserCrypto.ts:31:36)
      at new CryptoOps (node_modules/@azure/msal-browser/src/crypto/CryptoOps.ts:45:30)
      at PublicClientApplication.ClientApplication (node_modules/@azure/msal-browser/src/app/ClientApplication.ts:108:58)
      at new PublicClientApplication (node_modules/@azure/msal-browser/src/app/PublicClientApplication.ts:49:9)
      at Object.<anonymous> (src/App.test.tsx:12:22)
Run Code Online (Sandbox Code Playgroud)

我不确定上面的意思,但据我所知,发生此错误是因为会话未经身份验证。

因此,我的问题可以分为以下几个方面:

这个错误是什么意思?我该如何解决这个错误?(我们是否可以出于测试目的绕过 MSAL?)

jhm*_*jhm 4

您需要添加crypto到您的 Jest 配置中jest.config.js

module.exports = {
    // ...
    globals: {
        // ...
        crypto: require("crypto")
    }
};
Run Code Online (Sandbox Code Playgroud)