React-native-sound: Can't run unit tests with Jest

Created on 17 Aug 2017  路  5Comments  路  Source: zmxv/react-native-sound

While running a most simple unit test I get TypeError: Cannot read property 'IsAndroid' of undefined as in issue #36 . However, building and running the app works perfectly fine.

Mocking react-native-sound via jest.mock('react-native-sound'); doesn't help.

The test fails in line import myComponentWithANestedSubComponentWhichUsesRNSound from './'; of the following code snippet:

import 'react-native';
import React from 'react';
import renderer from 'react-test-renderer';

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

import myComponentWithANestedSubComponentWhichUsesRNSound from './';

describe('<ListItemVideo />', () => {

  it('renders correctly', () => {
    const tree = renderer.create(<myComponentWithANestedSubComponentWhichUsesRNSound />);
  });
});

question

Most helpful comment

@henninghall I guess you can apply same workaround as for react-native-i18n.

Basically create folder __mocks__ somewhere in your src folder (where jest has access) and create new file react-native-sound.js with:

export default function() {
  return 'Sound';
}

All 5 comments

Try:

jest.mock('react-native-sound', () => 'Sound')

@dominictracey your solution works fine when putting the mock in each test file. Is there any way to put it in a single place or do I have to put it in every test file I create?

@henninghall I guess you can apply same workaround as for react-native-i18n.

Basically create folder __mocks__ somewhere in your src folder (where jest has access) and create new file react-native-sound.js with:

export default function() {
  return 'Sound';
}

@mauron85 I dont understand how that is a valid mock. I still get the error.

TypeError: Sound.setCategory is not a function

which makes sense. How do I mock this package correctly in __mocks__?

If mocked it like:

jest.mock('react-native-sound', () => {
  class SoundMock {
    constructor(path, type, callback) {}
  }

  SoundMock.prototype.setVolume = jest.fn();
  SoundMock.prototype.setNumberOfLoops = jest.fn();
  SoundMock.prototype.play = jest.fn();
  SoundMock.prototype.stop = jest.fn();

  SoundMock.setCategory = jest.fn();

  return SoundMock;
});

and the check for function calls in my tests like

import Sound from 'react-native-sound';
...
expect(Sound.prototype.play).toHaveBeenCalled();

which seems to work for me. Maybe someone else finds it useful!

Was this page helpful?
0 / 5 - 0 ratings