Jest.js React Native:不变违例:`new NativeEventEmitter()`需要非空参数

2guxujil  于 2023-05-04  发布在  Jest
关注(0)|答案(1)|浏览(196)

我正在为一个特定的文件编写jest测试用例,该文件中有NativeModule导入。
在运行测试用例时,我得到以下错误:

● Test suite failed to run

    Invariant Violation: `new NativeEventEmitter()` requires a non-null argument.

      at invariant (node_modules/invariant/invariant.js:40:15)
      at new NativeEventEmitter (node_modules/react-native/Libraries/EventEmitter/NativeEventEmitter.js:45:7)
      at Object.<anonymous> (node_modules/react-native-quantum-metric-library/index.js:1:322)

在谷歌上搜索到上面的错误后,我做了一些修改,在测试文件中添加了以下代码。

jest.mock('react-native/Libraries/EventEmitter/NativeEventEmitter');

在添加了上面的行之后,我得到了以下错误:

Test suite failed to run

    TypeError: Cannot set properties of undefined (setting 'eventType')

      at Object.<anonymous> (node_modules/react-native-quantum-metric-library/index.js:1:367)

在再次谷歌搜索之后,我用下面的代码修改了上面的代码。

jest.mock('react-native/Libraries/EventEmitter/NativeEventEmitter.js', () => {
  const {EventEmitter} = require('events');
  return EventEmitter;
});

在上面的修改之后,我得到了下面的错误。

● Test suite failed to run

    TypeError: _reactNative.NativeEventEmitter is not a constructor

      at Object.<anonymous> (node_modules/react-native-quantum-metric-library/index.js:1:322)

有没有人可以帮我解决以上问题。

myzjeezk

myzjeezk1#

您需要在单元测试用例文件中模拟react-native-fs来解决依赖性问题。

jest.mock('react-native-fs', () => {
 return {
  mkdir: jest.fn(),
  moveFile: jest.fn(),
  copyFile: jest.fn(),
  pathForBundle: jest.fn(),
  pathForGroup: jest.fn(),
  getFSInfo: jest.fn(),
  getAllExternalFilesDirs: jest.fn(),
  unlink: jest.fn(),
  exists: jest.fn(),
  stopDownload: jest.fn(),
  resumeDownload: jest.fn(),
  isResumable: jest.fn(),
  stopUpload: jest.fn(),
  completeHandlerIOS: jest.fn(),
  readDir: jest.fn(),
  readDirAssets: jest.fn(),
  existsAssets: jest.fn(),
  readdir: jest.fn(),
  setReadable: jest.fn(),
  stat: jest.fn(),
  readFile: jest.fn(),
  read: jest.fn(),
  readFileAssets: jest.fn(),
  hash: jest.fn(),
  copyFileAssets: jest.fn(),
  copyFileAssetsIOS: jest.fn(),
  copyAssetsVideoIOS: jest.fn(),
  writeFile: jest.fn(),
  appendFile: jest.fn(),
  write: jest.fn(),
  downloadFile: jest.fn(),
  uploadFiles: jest.fn(),
  touch: jest.fn(),
  MainBundlePath: jest.fn(),
  CachesDirectoryPath: jest.fn(),
  DocumentDirectoryPath: jest.fn(),
  ExternalDirectoryPath: jest.fn(),
  ExternalStorageDirectoryPath: jest.fn(),
  TemporaryDirectoryPath: jest.fn(),
  LibraryDirectoryPath: jest.fn(),
  PicturesDirectoryPath: jest.fn()
 }
})

相关问题