Can't run unit tests with Jest
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 />);
});
});
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!
yeah this same error am also faced 2 hrs ago im fixed like: node_modules>react-native-sound>index.d.ts (open this folder) export = Sound; (put this command on your end of code in the index.d.ts) create a new folder on your root (Home) project. the folder named with mocks inside mocks folder u want to create a fie named react-native-sound.js inside of the react-native-sound.js you want to code like: // @flow
class Sound {}
export default Sound;
then save and run your project the error will solve
Try this;
jest.mock('react-native-sound', () => ({ setCategory: jest.fn(),