简体   繁体   中英

Jest import module, TypeError: Cannot read properties of undefined (reading 'utf16le')

I am trying to test a React component with Jest that imports a module called "Siwe", which is sign in with Ethereum.

My Jest config looks like this:

module.exports = {
  moduleNameMapper: {
    "module_name_(.*)":
      "<rootDir>/node_modules/apg-js/src/apg-conv-api/transformers.js",
  },
  transform: {
    "\\.[jt]sx?$": "babel-jest",
  },
  testEnvironment: "jsdom",
  transformIgnorePatterns: ['node_modules/(?!@wagmi)/"'],
};

My test code imports a react component, which has the following import:

import { SiweMessage } from "siwe";

If I remove the import, the test runs fine, but leaving the import in I get an error with the following stack trace

TypeError: Cannot read properties of undefined (reading 'utf16le')

  18 | import { signIn } from "next-auth/react";
  19 | import { AnimatePresence, motion } from "framer-motion";
> 20 | import { SiweMessage } from "siwe";
     | ^
  21 |
  22 | type Props = {};
  23 |

  at Object.utf16le [as decode] (node_modules/apg-js/src/apg-conv-api/transformers.js:801:21)
  at decode (node_modules/apg-js/src/apg-conv-api/converter.js:380:27)
  at Object.decode (node_modules/apg-js/src/apg-conv-api/converter.js:391:10)
  at new decode (node_modules/apg-js/src/apg-api/api.js:327:28)
  at Function.generateApi (node_modules/@spruceid/siwe-parser/dist/abnf.js:154:21)
  at Object.generateApi (node_modules/@spruceid/siwe-parser/dist/abnf.js:166:28)
  at Object.require (node_modules/@spruceid/siwe-parser/dist/parsers.js:18:16)
  at Object.require (node_modules/siwe/dist/client.js:37:23)
  at Object.require (node_modules/siwe/dist/siwe.js:17:14)
  at Object.<anonymous> (pages/playground.page.tsx:20:1)
  at Object.<anonymous> (__tests__/playground.test.tsx:2:1)

For th life of me, I cannot figure out what the problem is.

Module node_modules/apg-js/src/apg-conv-api/transformers.js goes through jest's transformer. Jest wraps code in self executed functions that break apg-conv-api/transformers.js because it relies on correct this reference inside the module .

But the root problem in incorrect transformIgnorePatterns as I guess you want to ignore transform for all node_modules except @wagmi if yes just replace it to:

{
  ...
  transformIgnorePatterns: ['node_modules/(?!@wagmi/)'],
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM