简体   繁体   中英

How to mock the imported "package.json" in Jest?

My React application refers version in the imported package.json .

import pjson from './package.json';

// snip

<p>Version: ${pjson.version}</p>

In the example above, Jest would display an error message like this:

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

  69 |
> 70 |     <p>Version: v{pjson.version}</p>
     |                         ^

How can I mock this up?

Just importing with asterisks solved the problem.
Neither mock nor moduleNameMapper is needed.

  • src/App.tsx
import * as pjson from './package.json';

I made these files. But the same.

jest.config.ts :

const config: Config.InitialOptions = {
  moduleNameMapper: {
    '^.+\\.json$': '<rootDir>/__mocks__/mock.json',
  },
};

__mocks__/mock.json :

{
  "version": "0"
}

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