Can't mock reaction-native sound with Jest

When I try to make fun of react-native-sound with Jest, I get the following error:

//PlayerService.js
import Sound from 'react-native-sound';

try {
  console.log('Sound: ' + JSON.stringify(Sound)); //Sound: {}
  _trackPlaying = new Sound('path', Sound.LIBRARY, error => { });
} catch (error) {
  console.log('error: ' + JSON.stringify(error)); //error: {}
}
//PlayerService.tests.js
jest.mock('react-native-sound', () => ({
  Sound: jest.fn((path, type, callback) => {

  })
}));

//package.json

{
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-jest": "^21.2.0",
    "babel-plugin-transform-flow-strip-types": "^6.22.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-flow": "^6.23.0",
    "flow": "^0.2.3",
    "jest": "^21.2.1"
  },
  "jest": {
    "modulePathIgnorePatterns": [
      "__mocks__/"
    ]
  },
  "dependencies": {
    "react-native-sound": "^0.10.4"
  }
}

As an alternative, I tried setting up a manual layout in a separate file ( __mock__) with a similar hit:

//__mocks__/react-native-sound.js
const Sound = jest.genMockFromModule('react-native-sound');

Sound = (path, type, callback) => {
  console.log("mocked");
}

module.exports = Sound;

//__tests__/PlayerService.tests.js
jest.mock('react-native-sound'); // doesn't work

Any recommendations or recommendations are welcome. Many thanks!

+4
source share
2 answers

Well, I found the problem at the end.

The way I tried to make the layout was a problem, so I did to return a new function that mimics what I need to taunt:

jest.mock('react-native-sound', () => {
  var _filename = null;
  var _basePath = null;

  var SoundMocked = (filename, basePath, onError, options) => {
    _filename = filename;
    _basePath = basePath;
    onError();
  }

  SoundMocked.prototype.filename = () => _filename;
  SoundMocked.prototype.basePath = () => _basePath;
  SoundMocked.prototype.play = function (onEnd) { };
  SoundMocked.prototype.pause = function (callback) { };
  SoundMocked.prototype.stop = function (callback) { };
  SoundMocked.prototype.reset = function () { };
  SoundMocked.prototype.release = function () { };
  SoundMocked.prototype.getDuration = function () { };

  SoundMocked.LIBRARY = 2;

  return SoundMocked;
});
0
source

, . . , , Sound.LIBRARY, . , , , , genMockFromModule . , , . babel ES6, , .

- .,.

// __mocks__/react-native-sound.js

class Sound {
  constructor(path, type, callback) {
    ...
  }

  LIBRARY = 1
}

export Sound;

jest.mock('react-native-sound');

-native ( , mocks , , ), , NameMapper , , . , .

"moduleNameMapper": {
  "react-native-sound": "<rootDir>/__mocks__/react-native-sound.js"
}

, - - undefined, , .

, es5, .

+1

Source: https://habr.com/ru/post/1689662/


All Articles