GithubHelp home page GithubHelp logo

realorangeone / react-native-mock Goto Github PK

View Code? Open in Web Editor NEW
570.0 22.0 153.0 335 KB

A fully mocked and test-friendly version of react native (maintainers wanted)

License: MIT License

JavaScript 100.00%
react react-native react-native-mock testing

react-native-mock's Introduction

Interested in helping maintain react-native-mock? Reach out!

react-native-mock Build Status

Join the chat at https://gitter.im/RealOrangeOne/react-native-mock A fully mocked and test-friendly version of react native

Requirements

  • Node.js 4+
  • The latest version of react-native

Note: This library is designed to work with the most recent version of react-native. If you aren't using the most recent version, you will need to download an older version of this library, as the API is likely to be different, and the dependencies are likely to break.

How Am I Supposed To Use This?

npm i react-native-mock --save-dev
/* file-that-runs-before-all-of-my-tests.js */

// This will mutate `react-native`'s require cache with `react-native-mock`'s.
require('react-native-mock/mock'); // <-- side-effects!!!

Why?

Testing React Native components is hard. I'm hoping this makes it easier.

I wrote a React Testing Library that works really well for React "Web", but didn't really work for React "Native" without something like this.

Wait... Is this actually a terrible idea?

I don't know. Maybe.

I'd love to figure that out though... feel free to file an issue if you have opinions.

Contributing

Discovered a bug, got a new feature, or found something that needs improving? Submit a PR!

Make sure to read through the CONTRIBUTING.md file before submitting your PR!

Core Contributors

What do the labels mean?

See this wiki page.

react-native-mock's People

Contributors

amwam avatar andrey-skl avatar arian avatar bdougie avatar bob-carson avatar christopherdro avatar danivovich avatar dingbat avatar feyy avatar fritzmonkey avatar gitter-badger avatar jeiwan avatar jhen0409 avatar joemckie avatar keokilee avatar lelandrichardson avatar lulutia avatar mroswald avatar newtonry avatar omeid avatar p16 avatar pgom avatar realorangeone avatar sibelius avatar taylesworth avatar viceversus avatar zaubernerd avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-mock's Issues

SyntaxError: Unexpected token import

ChatList.js

import React from 'react';
import {
  View,
  Text,
} from 'react-native';

const ChatList = () => (
  <View>
    <Text>Hello world</Text>
  </View>
);

export default ChatList;

ChatList.test.js

import React from 'react';
import { View } from 'react-native';
import { shallow } from 'enzyme';
import { expect } from 'chai';
import { describe, it } from 'mocha';

import ChatList from './ChatList';

describe('ChatList', () => {
  it('should render ChatList', () => {
    const wrapper = shallow(<ChatList />);
    expect(wrapper.find(View).length).to.equal(1);
  });
});

test command

mocha --require react-native-mock/mock.js --compilers js:babel-core/register --recursive src/**/*.test.js

at this point, works fine!

in here, i am trying to use an third party libaray component.

https://github.com/GeekyAnts/NativeBase

added this line

import { Container, Header, Content, Footer, Title } from 'native-base';

and run test

> mocha --require react-native-mock/mock.js --compilers js:babel-core/register --recursive src/**/*.test.js


node_modules/native-base/index.js:4
import Header from './Components/Widgets/Header';
^^^^^^

SyntaxError: Unexpected token import
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:374:25)
    at Module._extensions..js (module.js:405:10)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/canna/my-projects/mshopbang/node_modules/babel-register/lib/node.js:166:7)
    at Module.load (module.js:344:32)
    at Function.Module._load (module.js:301:12)
    at Module.require (module.js:354:17)

sounds like the it cannot understand the es6 syntax import

Is there a solution to this?

Seems like the only solution is that, change all the import to require syntax....

ReferenceError: window is not defined

There are two calls to window.cancelAnimationFrame in AnimatedImplementation.js.

This causes ReferenceError: window is not defined when I run my tests, and I can't mock window because other libraries (like sinon) enable React Native compatibility by checking for window.

How to access elements inside <TouchableOpacity .. /> ?

I'm trying to test a simple component, where some areas are wrapped with

          <View style={styles.fieldContainer}>
            <TouchableOpacity onPress={() => {onPressHandler(...);}}>
              <IXText text={inputTime}  />
            </TouchableOpacity>
          </View>

I've tried different methods and rendering functions, it only can find/traverse to TouchableOpacity element, but not children inside it? Is it a problem of react-native-mock or enzyme?

Any ideas on how to test this component?

Can't install

I ran the install command as per the README:

npm ERR! peerinvalid The package [email protected] does not satisfy its siblings' peerDependencies requirements!
npm ERR! peerinvalid Peer [email protected] wants react@*
npm ERR! peerinvalid Peer [email protected] wants [email protected]

Not really sure why it's being like that, could you possibly remove react as a peerDependency?

Thanks for creating this, by the way ๐Ÿ˜„

Publish new version to npm

Just wondering when the next version will be published to npm? Since I'll be using this with Travis I'd prefer not to have to pull master. Using NavigationExperimental so I need the newer version.

New npm release

The current release is not compatible with 0.33.0+ of react native. (Mostly due to PropType warnings, but still)

Would love to see a new release soon!

Example Project

Hi there,

First of all thanks for this idea, it is exactly the point I am currently struggling with testing my react native application. I just wanted to ask if you have a project on github which uses this mock, I would love to see it in action somewhere.

Have a nice day!

Cannot find module 'keyMirror'

After cloning the repository and running npm install. I tried to run npm test and this error showed up.

[email protected] test /home/pranjal/react-native-mock
mocha --require babel-core/register test/*/.js

module.js:328
throw err;
^

Error: Cannot find module 'keyMirror'
at Function.Module._resolveFilename (module.js:326:15)
at Function.Module._load (module.js:277:25)
at Module.require (module.js:354:17)
at require (internal/module.js:12:17)
at Object. (/home/pranjal/react-native-mock/src/api/InteractionManager.js:3:18)
at Module._compile (module.js:410:26)
at loader (/home/pranjal/react-native-mock/node_modules/babel-register/lib/node.js:134:5)
at Object.require.extensions.(anonymous function) as .js
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Module.require (module.js:354:17)
at require (internal/module.js:12:17)
at Object. (/home/pranjal/react-native-mock/src/api/Animated/AnimatedImplementation.js:21:27)
at Module._compile (module.js:410:26)
at loader (/home/pranjal/react-native-mock/node_modules/babel-register/lib/node.js:134:5)
at Object.require.extensions.(anonymous function) as .js
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Module.require (module.js:354:17)
at require (internal/module.js:12:17)
at Object. (/home/pranjal/react-native-mock/src/api/Animated/index.js:21:31)
at Module._compile (module.js:410:26)
at loader (/home/pranjal/react-native-mock/node_modules/babel-register/lib/node.js:134:5)
at Object.require.extensions.(anonymous function) as .js
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Module.require (module.js:354:17)
at require (internal/module.js:12:17)
at Object. (react-native.js:55:13)
at Module._compile (module.js:410:26)
at loader (/home/pranjal/react-native-mock/node_modules/babel-register/lib/node.js:134:5)
at Object.require.extensions.(anonymous function) as .js
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Module.require (module.js:354:17)
at require (internal/module.js:12:17)
at Object. (/home/pranjal/react-native-mock/test/basic-test.js:3:20)
at Module._compile (module.js:410:26)
at loader (/home/pranjal/react-native-mock/node_modules/babel-register/lib/node.js:134:5)
at Object.require.extensions.(anonymous function) as .js
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Module.require (module.js:354:17)
at require (internal/module.js:12:17)
at /home/pranjal/react-native-mock/node_modules/mocha/lib/mocha.js:219:27
at Array.forEach (native)
at Mocha.loadFiles (/home/pranjal/react-native-mock/node_modules/mocha/lib/mocha.js:216:14)
at Mocha.run (/home/pranjal/react-native-mock/node_modules/mocha/lib/mocha.js:468:10)
at Object. (/home/pranjal/react-native-mock/node_modules/mocha/bin/_mocha:403:18)
at Module._compile (module.js:410:26)
at Object.Module._extensions..js (module.js:417:10)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Function.Module.runMain (module.js:442:10)
at startup (node.js:136:18)
at node.js:966:3
npm ERR! Test failed. See above for more details.

Mocking platform-agnostic requires

React Native does some magic around requires to allow require(img.png) as pointed out in #11, but it also allows platform-specific components to be named with an extension .ios.js or .android.js, and then be imported with a simple import {MyComponent} from 'my-component.js'; (http://facebook.github.io/react-native/docs/platform-specific-code.html#platform-specific-extensions). This avoids the need to sprinkle Platform.OS ternaries throughout the code, but of course Node has no idea how to resolve the import/require and blows up.

Do you have any suggestions or ideas of the best way to handle this?

Upgrade react-native 0.27.1 error

Failed to build DependencyGraph: @providesModule naming collision:
Duplicate module name: ViewportMetrics
Paths: /Users/caolicheng/workspace/reading/node_modules/react-native-mock/node_modules/react/lib/ViewportMetrics.js collides with /Users/caolicheng/workspace/reading/node_modules/react/lib/ViewportMetrics.js

This error is caused by a @providesModule declaration with the same name accross two different files.
Error: @providesModule naming collision:
Duplicate module name: ViewportMetrics
Paths: /Users/caolicheng/workspace/reading/node_modules/react-native-mock/node_modules/react/lib/ViewportMetrics.js collides with /Users/caolicheng/workspace/reading/node_modules/react/lib/ViewportMetrics.js

This error is caused by a @providesModule declaration with the same name accross two different files.
at HasteMap._updateHasteMap (/Users/caolicheng/workspace/reading/node_modules/node-haste/lib/DependencyGraph/HasteMap.js:162:15)
at /Users/caolicheng/workspace/reading/node_modules/node-haste/lib/DependencyGraph/HasteMap.js:127:25

Deploy new version

I noticed there are some commits that have not been released, my tests are failing due to this and I would prefer not to fork the library. Is there a reason that a new release is not published? Anything I can do to help with releasing a new version?

"What's missing" script

I think we need to create an issue with a checklist for each new version of react native so we can track what is missing in react-native-mock to use the latest version

Any interest in exposing or extracting utilities?

Thank you for this project! It's been very helpful and works great!

While this project works for the core React Native components, it doesn't help with other native components (such as react-native-camera). However, the utilities and approach taken here work just fine with other components.

Is there any interest in exposing some utilities from this library, or extracting them to a different library and then using them from here?

I'm thinking particularly of createMockComponent and the code in mock.js, but there may be other reusable helpers as well.

In my project, I extracted a function out of mock.js that looks like this:

function registerNativeMock(pkg, component) {
  const key = require.resolve(pkg);

  require.cache[key] = {
    id: key,
    filename: key,
    loaded: true,
    exports: component
  };
}

Using this function, mock.js would end up looking like this:

const ReactNativeMock = require('./build/react-native');

registerNativeMock('react-native', ReactNativeMock);

If this idea is of interest, let me know which direction you'd like to go (expose or extract), and I'll be happy to put together a PR.

Also, if you can identify any additional utilities that might be useful when mocking other libraries, point them out and I'll include them.

Publish latest version to NPM

Hello,

Had a PR which was merged last week, any chance you could publish the latest version to NPM?
CI tests are currently failing.

Thank you

handling react-native updates?

Thanks for all of the work on this! After spending a lot of time struggling with Jest and the react-native docs (v 0.27.0) for setting up unit tests, I decided to give enzyme w/ mocha/chai a go and bam, I was up and running tests that matter to me.

I'm wondering what the process is like if/when react-native updates offer new functionality or breaking changes. Is there any coordination between you all and the react-native deployment process?

I expect the react-native docs for setting up tests for our app code will improve over time, but until then I'm happy to stick with these mocks and deal with additional app specific needs as they arise. I just want to know if there will be documentation or anything that will help us determine which versions of react-native-mock are stable/usable with corresponding versions of react-native. I guess the ideal situation is that part of the react-native deployment process includes the updated, matching, and battle-tested mocks :)

Thanks again, and sorry if any of this has already been discussed in other/old issues. I didn't see anything about it immediately aside from the note about more information soon in the readme.

Asserting interactions with react native mocks

Hi,
I'm new to React Native so excuse me if this question has an obvious solution but I couldn't find it.

I'm trying to verify interactions with React Native components. In my case I have a Navigator passed to my component and I use it as so:

class BackText extends Component {
  render() {
    return (
      <Text onPress={() => this.props.navigator.pop()}>back</Text>
    );
  }
}

I'm trying to build my unit test around this component but I'm not sure which Navigator to pass to my component.
I tried importing the Navigator from either react-native or react-native-mock and initiate them in my tests but neither had a pop method (or other Navigator methods).

Of course I can bypass the problem by setting up my own class with one pop method that I will be spying on but I'm trying to avoid re-mocking the RN API.

What's the preferred way of verifying interactions with the RN mocked components?

Thank you

Path in ART has unmocked methods

The Path class in the ART library is only partially mocked out. I'd like to mock out the rest of the methods for my own selfish reasons.

I'll have a PR up by the end of the day.

Understanding react-native-mock and react-native testing

Hi Leland,

We've crossed some tweets beforehand, but as usual Twitter character limits don't help. Thanks for offering your help, really appreciated.

The app we are building is using mostly RN + redux. Redux reducers and actions were easy to test using a combination of Mocha + Proxyquire + Sinon + Chai

However, some logic is still in the components as you know, so I wanted to test them. At the beginning of this week I read this article and somebody mentioned react-native-mock in the comments, it made sense to me.

First, As I mentioned to you in Twitter, when I install enzyme or react-native-mock with RN 0.20.0-rc (this is what I'm using currently) I get name collisions when I do react-native start for launching the packager. I understand I don't need the packager for the tests at all, but when I stop testing and start coding I launch the packager. In order to get it working I need to remove react and react-native-mock folders.

captura de pantalla 2016-02-17 a las 10 51 35

Second, my component testing isn't going as I was expecting. I've been able to test a very simple test component I created, however our components are composed of several nested components and have many which rely on native parts. With proxyquire, which sometimes is a little rough, I manage to mock this native parts, however it looks like shallow enzyme has trouble with them.

My test skeleton looks like this:

import React from "react";
const proxyquire = require('proxyquire').noCallThru()
const sinon = require('sinon')
import { shallow } from "enzyme";
require('react-native-mock/mock')


describe.only("<DrawerOption />", () => {

  let DrawerOption

  beforeEach(() => {
    DrawerOption = proxyquire('geminis/src/components/drawer/DrawerOption', {
      'several mocks go here': function() {
        return sinon.spy();
      },
    })
  })

  it("Render basic DrawerOption without props", () => {
    console.log(DrawerOption)
    let wrapper = shallow(<DrawerOption />);
    expect(wrapper.find('View')).to.have.length(1);
  });
});

My console.log throws:

{ [Function] displayName: 'DrawerOption' }

However the test breaks with:

TypeError: Cannot read property 'propTypes' of undefined

I'm aware there are probably better ways than proxyquire, but I'm quite new to all this. Any hints about the first and second problem would be great.

Thanks for your open source work with this project and enzyme ๐Ÿ‘

Cheers,
Miguel

InteractionManager.createInteractionHandle is not a function

The minimal mocha test suite to reproduce this problem is following:

// tests/animatedTest.js
import {Animated} from 'react-native'

describe('Animated', () => {
  it('should animate', () => {
    const value = new Animated.Value(0)
    Animated.timing(
      value,
      {
        toValue: 1,
        delay: 1000
      }
    ).start()
  })
})

When running with:

mocha --require react-native-mock/mock --compilers js:babel-core/register tests/animatedTest.js       

I get the following error:

     TypeError: _InteractionManager2.default.createInteractionHandle is not a function
      at AnimatedValue.animate (node_modules/react-native-mock/build/api/Animated/AnimatedImplementation.js:750:52)
      at Object.start (node_modules/react-native-mock/build/api/Animated/AnimatedImplementation.js:1543:23)
      at Context.<anonymous> (animatedTest.js:12:7)

It looks like InteractionManager.js is missing module.exports statement.

Node haste throws when building app

It happends when I try to build with dev deps (e.g. react-native-mock and react-native with react are inside of ./node_modules)

Just take a look on this log:

Failed to build DependencyGraph: @providesModule naming collision:
  Duplicate module name: AutoFocusUtils
  Paths: /foo/node_modules/react-native-mock/node_modules/react/lib/AutoFocusUtils.js collides with /foo/node_modules/react/lib/AutoFocusUtils.js

This error is caused by a @providesModule declaration with the same name accross two different files.
Error: @providesModule naming collision:
  Duplicate module name: AutoFocusUtils
  Paths: /foo/node_modules/react-native-mock/node_modules/react/lib/AutoFocusUtils.js collides with /foo/node_modules/react/lib/AutoFocusUtils.js

This error is caused by a @providesModule declaration with the same name accross two different files.
    at HasteMap._updateHasteMap (/foo/node_modules/node-haste/lib/DependencyGraph/HasteMap.js:160:15)
    at /foo/node_modules/node-haste/lib/DependencyGraph/HasteMap.js:125:25
:app:bundleReleaseJsAndAssets FAILED

@providesModule is a Node haste thing, but I can't find real docs for it. It's needed for build step, but does react-native-mock really needs these module ids? This module is used in testing purposes, and with this declarations we forced to remove this module every build ...

May be just remove those declarations and everything will be fine? react-native-mock is used by jest.setMock or as mock in __mocks__ directory, so I think, @providesModule really is not needed.

RN 0.33.0 Conflicts with react-native/lib/* ?

As of React Native 0.33.0, my build started failing as it could not find the react-native/lib/* files. Example:

Cannot find module 'deepDiffer'

I've gotten around this with mockery:

mockery.registerMock('react-native/lib/deepDiffer', () => null);
mockery.registerMock('react-native/lib/flattenStyle', () => null);
mockery.registerMock('react-native/lib/InitializeJavaScriptAppEngine', () => null);
mockery.registerMock('react-native/lib/RCTEventEmitter', () => null);
mockery.registerMock('react-native/lib/TextInputState', () => null);
mockery.registerMock('react-native/lib/UIManager', () => null);
mockery.registerMock('react-native/lib/UIManagerStatTracker', () => null);
mockery.registerMock('react-native/lib/View', () => null);
mockery.registerMock('react-native/lib/deepFreezeAndThrowOnMutationInDev', () => null);

While this got past the above errors, it prompted a new one:

Error: Cannot find module 'BoundingDimensions'

I assume these to be issues with RN 0.33.0?

CircleCI error: ReferenceError: Map is not defined

I know this project is very new and would like to help where I can, but just need to know if this error is legit on my CircleCI. My tests pass locally but fail on CircelCI.

I believe the new Map() is part of the Standard JavaScript API, but my error is ReferenceError: Map is not defined.

Curious to see if anyone has used react-native-mock with CircleCI and if there is a work around. I also understand that this might not be correct forum for this type of question, and have also open up a Stack Overflow question on this.

I saw there is also a TravisCI #25 issue open, but do not see it as related.

CircleCI error:

npm test

> [email protected] test /home/ubuntu/Messenger
> mocha --require react-native-mock/mock.js --compilers js:babel-core/register --recursive App/**/__tests__/*.test.js

> mocha --require react-native-mock/mock.js --compilers js:babel-core/register --recursive App/**/__tests__/*.test.js


/home/ubuntu/Messenger/node_modules/react-native-mock/build/api/AppState.js:18
  change: new Map(),
              ^
ReferenceError: Map is not defined
    at Object.<anonymous> (/home/ubuntu/Messenger/node_modules/react-native-mock/build/api/AppState.js:18:15)
    at Module._compile (module.js:456:26)
    at Module._extensions..js (module.js:474:10)
    at Object.require.extensions..js (/home/ubuntu/Messenger/test/compiler.js:12:49)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (/home/ubuntu/Messenger/node_modules/react-native-mock/build/react-native.js:66:13)
    at Module._compile (module.js:456:26)
    at Module._extensions..js (module.js:474:10)
    at Object.require.extensions..js (/home/ubuntu/Messenger/test/compiler.js:12:49)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (/home/ubuntu/Messenger/node_modules/react-native-mock/mock.js:1:85)
    at Module._compile (module.js:456:26)
    at Module._extensions..js (module.js:474:10)
    at Object.require.extensions..js (/home/ubuntu/Messenger/test/compiler.js:12:49)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at args (/home/ubuntu/nvm/v0.10.33/lib/node_modules/mocha/bin/_mocha:310:3)
    at Array.forEach (native)
    at Object.<anonymous> (/home/ubuntu/nvm/v0.10.33/lib/node_modules/mocha/bin/_mocha:309:10)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:906:3
npm ERR! Test failed.  See above for more details.

npm test returned exit code 1

Touchable mocks

Using this library, is it possible to simulate touch events, for example clicking on a TouchableHighlight ?
I am making use of enzyme with mocha and chain, but not sure how to approach this.

Here is an example of what I am trying:

<Component>
  <View>
    <TouchableHighlight onPress={this.props.buttonPressed}>
      <Text>{this.props.text}</Hello>
    </TouchableHighlight>
  </View>
</Component>

  it('should be pressed', () => {
    let buttonPressed = sinon.spy();
    let wrapper = shallow(<Component text={'Hello'} onPress={buttonPressed} />);
    wrapper.children().forEach( n => {
        n.simulate('click')});
    expect(onButtonClick.calledOnce).to.equal(true);
  });

Fix Travis setup

Hi there,

Thanks again for this great lib. I was just curious if you would mind fixing your travis setup? A simple travis.yml with language: node_js should work as it automatically runs npm install and npm test.

Have a nice day!

Problem with ListView using enzyme

Given the following simple component using a ListView:

var React = require('react-native');
var {
  ListView,
  Text,
  } = React;

export default React.createClass({
  getInitialState: function () {
    var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    return {
      dataSource: ds.cloneWithRows(['row 1', 'row 2']),
    };
  },

  render: function () {
    return (
      <ListView
        dataSource={this.state.dataSource}
        renderRow={(rowData) => <Text>{rowData}</Text>}
      />
    );
  }
})

The following Mocha spec throws a TypeError: ListView.DataSource is not a function in the getInitialState function.

/* global React, shallow, mount, _, expect */

import ListViewSimpleExample from './ListViewSimpleExample';

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

  it('should render stuff', () => {
    const wrapper = shallow(<ListViewSimpleExample/>);
    console.log(wrapper.debug());
  });
});

What could be the cause?

My test environment:

package.json (abbreviated):

  "dependencies": {
    "react-native": "0.19.0",
  },
  "devDependencies": {
    "babel-preset-react-native": "^1.4.0",
    "enzyme": "^2.0.0",
    "mocha": "^2.4.5",
    "react-addons-test-utils": "^0.14.7",
    "react-dom": "^0.14.7",
    "react-native-mock": "0.0.6",
  }
}

.babelrc:

{
  "presets": ["react-native"]
}

Other simple specs (only using View and Text) work fine, so it seems not to be a general problem.

Enzyme's mount() failed when trying to render Animated.View

Hi,
I'm trying to test component which has Animated.View, but when I call the enzyme's mount() I'm getting an error TypeError: Cannot read property '__getValue' of undefined

the full stack is:
TypeError: Cannot read property '__getValue' of undefined
at AnimatedComponent.render (C:\Git{xxx}{aaa}\reactNativeSrc\node_modules\react-native-mock\build\api\Animated\createAnimatedComponent.js:10:20)
at [object Object].ReactCompositeComponentMixin._renderValidatedComponentWithoutOwnerOrContext (C:\Git{xxx}{aaa}\reactNativeSrc\node_modules\react\lib\ReactCompositeComponent.js:687:34)
at [object Object].ReactCompositeComponentMixin._renderValidatedComponent (C:\Git{xxx}{aaa}\reactNativeSrc\node_modules\react\lib\ReactCompositeComponent.js:707:32)
at [object Object].wrapper as _renderValidatedComponent
at [object Object].ReactCompositeComponentMixin.performInitialMount (C:\Git{xxx}{aaa}\reactNativeSrc\node_modules\react\lib\ReactCompositeComponent.js:291:30)
at [object Object].ReactCompositeComponentMixin.mountComponent (C:\Git{xxx}{aaa}\reactNativeSrc\node_modules\react\lib\ReactCompositeComponent.js:222:21)
at [object Object].wrapper as mountComponent
at Object.ReactReconciler.mountComponent (C:\Git{xxx}{aaa}\reactNativeSrc\node_modules\react\lib\ReactReconciler.js:39:35)
at [object Object].ReactCompositeComponentMixin.performInitialMount (C:\Git{xxx}{aaa}\reactNativeSrc\node_modules\react\lib\ReactCompositeComponent.js:297:34)
at [object Object].ReactCompositeComponentMixin.mountComponent (C:\Git{xxx}{aaa}\reactNativeSrc\node_modules\react\lib\ReactCompositeComponent.js:222:21)
at [object Object].wrapper as mountComponent
at Object.ReactReconciler.mountComponent (C:\Git{xxx}{aaa}\reactNativeSrc\node_modules\react\lib\ReactReconciler.js:39:35)
at [object Object].ReactCompositeComponentMixin.performInitialMount (C:\Git{xxx}{aaa}\reactNativeSrc\node_modules\react\lib\ReactCompositeComponent.js:297:34)
at [object Object].ReactCompositeComponentMixin.mountComponent (C:\Git{xxx}{aaa}\reactNativeSrc\node_modules\react\lib\ReactCompositeComponent.js:222:21)
at [object Object].wrapper as mountComponent
at Object.ReactReconciler.mountComponent (C:\Git{xxx}{aaa}\reactNativeSrc\node_modules\react\lib\ReactReconciler.js:39:35)
at [object Object].ReactCompositeComponentMixin.performInitialMount (C:\Git{xxx}{aaa}\reactNativeSrc\node_modules\react\lib\ReactCompositeComponent.js:297:34)
at [object Object].ReactCompositeComponentMixin.mountComponent (C:\Git{xxx}{aaa}\reactNativeSrc\node_modules\react\lib\ReactCompositeComponent.js:222:21)
at [object Object].wrapper as mountComponent
at Object.ReactReconciler.mountComponent (C:\Git{xxx}{aaa}\reactNativeSrc\node_modules\react\lib\ReactReconciler.js:39:35)
at mountComponentIntoNode (C:\Git{xxx}{aaa}\reactNativeSrc\node_modules\react\lib\ReactMount.js:103:32)
at ReactReconcileTransaction.Mixin.perform (C:\Git{xxx}{aaa}\reactNativeSrc\node_modules\react\lib\Transaction.js:136:20)
at batchedMountComponentIntoNode (C:\Git{xxx}{aaa}\reactNativeSrc\node_modules\react\lib\ReactMount.js:124:15)
at ReactDefaultBatchingStrategyTransaction.Mixin.perform (C:\Git{xxx}{aaa}\reactNativeSrc\node_modules\react\lib\Transaction.js:136:20)
at Object.ReactDefaultBatchingStrategy.batchedUpdates (C:\Git{xxx}{aaa}\reactNativeSrc\node_modules\react\lib\ReactDefaultBatchingStrategy.js:63:19)
at Object.batchedUpdates (C:\Git{xxx}{aaa}\reactNativeSrc\node_modules\react\lib\ReactUpdates.js:97:20)
at Object.ReactMount._renderNewRootComponent (C:\Git{xxx}{aaa}\reactNativeSrc\node_modules\react\lib\ReactMount.js:277:18)
at Object.wrapper as _renderNewRootComponent
at Object.ReactMount._renderSubtreeIntoContainer (C:\Git{xxx}{aaa}\reactNativeSrc\node_modules\react\lib\ReactMount.js:354:32)
at Object.ReactMount.render (C:\Git{xxx}{aaa}\reactNativeSrc\node_modules\react\lib\ReactMount.js:374:23)
at Object.wrapper as render
at Object.ReactTestUtils.renderIntoDocument (C:\Git{xxx}{aaa}\reactNativeSrc\node_modules\react\lib\ReactTestUtils.js:78:21)
at renderWithOptions (C:\Git{xxx}{aaa}\reactNativeSrc\node_modules\enzyme\build\react-compat.js:175:26)
at new ReactWrapper (C:\Git{xxx}{aaa}\reactNativeSrc\node_modules\enzyme\build\ReactWrapper.js:94:59)
at mount (C:\Git{xxx}{aaa}\reactNativeSrc\node_modules\enzyme\build\mount.js:21:10)
at Context. (ContactSupportInputContainerSpec.js:213:25)
at callFn (C:\Git{xxx}{aaa}\reactNativeSrc\node_modules\mocha\lib\runnable.js:326:21)
at Test.Runnable.run (C:\Git{xxx}{aaa}\reactNativeSrc\node_modules\mocha\lib\runnable.js:319:7)
at Runner.runTest (C:\Git{xxx}{aaa}\reactNativeSrc\node_modules\mocha\lib\runner.js:422:10)
at C:\Git{xxx}{aaa}\reactNativeSrc\node_modules\mocha\lib\runner.js:528:12
at next (C:\Git{xxx}{aaa}\reactNativeSrc\node_modules\mocha\lib\runner.js:342:14)
at C:\Git{xxx}{aaa}\reactNativeSrc\node_modules\mocha\lib\runner.js:352:7
at next (C:\Git{xxx}{aaa}\reactNativeSrc\node_modules\mocha\lib\runner.js:284:14)
at Immediate._onImmediate (C:\Git{xxx}{aaa}\reactNativeSrc\node_modules\mocha\lib\runner.js:320:5)

please advice,
Noam

`done` is not a function

React native has a non-standard extension to Promise. It adds a done method that throws any uncaught errors. Unless I am mistaken, I don't believe react-native-mock adds this. Are there plans to do this?

PropType warnings with RN 0.32.0

I've recently upgraded to RN 0.32.0 and now I'm getting warnings in all my tests.

e.g.

...

Warning: You are manually calling a React.PropTypes validation function for the `style` prop on `View`. This is deprecated and will not work in the next major version. You may be seeing this warning due to a third-party PropTypes library. See https://fb.me/react-warning-dont-call-proptypes for details.

Warning: You are manually calling a React.PropTypes validation function for the `transformMatrix` prop on `View`. This is deprecated and will not work in the next major version. You may be seeing this warning due to a third-party PropTypes library. See https://fb.me/react-warning-dont-call-proptypes for details.

...

After reading the link they provided (https://fb.me/react-warning-dont-call-proptypes) and looking at some code, it seems like the way styles and transforms are done do violate their new rules. I'm not sure how to best fix it.

Any ideas?

What about images?

I have a file where I require images, but I get the error:

Error: Cannot find module '../Images/Logo/some_image.png'
    at Function.Module._resolveFilename (module.js:338:15)

any way we can mock this?

Issues with mocking interfering with 3rd-party node modules

I'm having some issues getting a basic test to compile. I'm fairly new to React Native / Mocha / Babel so any insight would be helpful.

I followed your advice regarding forcing babel to compile node modules here, with some modifications of my own due to some problematic modules. However, now the issue seems to be that there is a conflict between react-native-mock getting in the way of an external node module ("react-native-router-flux" in this case) from functioning properly.

Any thoughts would be greatly appreciated!

/* .babelrc */

{ 
  "presets": ["stage-1", "react-native"]
}
/* MyComponent.js */

'use strict';

var React = require('react-native');
var {View, Text, StyleSheet, TouchableHighlight} = React;
var Button = require('react-native-button');
var Actions = require('react-native-router-flux').Actions;

class MyComponent extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.baseText}>Test!</Text>
        <Button onPress={()=>Actions.login({data:"Custom data", title:'Custom title' })}>Go to Login page</Button>
        <Button onPress={Actions.signup}>Go to Register page</Button>
      </View>
    );
  }
}

var styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: 'transparent',
    },
    baseText: {
      fontFamily: 'Raleway-Regular'
    }
});

module.exports = MyComponent;
/* MyComponent_spec.js */

import React from 'react';
import { shallow } from 'enzyme';
import { View, Text, StyleSheet } from 'react-native';

import MyComponent from '../../../react/components/ecosystems/MyComponent';

describe("<MyComponent/>", () => {
  it('should render', () => {
    const wrapper = shallow(<MyComponent />);
    expect(wrapper).to.be.ok;
  });
});
/* package.json */

{
  "name": "Test",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "mocha --require ./test/setup.js --compilers js:babel-core/register 'test/**/*.@(js|jsx)'"
  },
  "dependencies": {
    "immutable": "^3.7.6",
    "react-native": "^0.21.0",
    "react-native-button": "^1.4.2",
    "react-native-router-flux": "^2.3.12",
    "react-redux": "^4.4.0",
    "redux": "^3.3.1"
  },
  "devDependencies": {
    "babel-cli": "^6.6.5",
    "babel-core": "^6.7.2",
    "babel-plugin-transform-es2015-modules-commonjs": "^6.7.0",
    "babel-polyfill": "^6.7.2",
    "babel-preset-es2015": "^6.6.0",
    "babel-preset-react": "^6.5.0",
    "babel-preset-react-native": "^1.5.2",
    "babel-preset-stage-1": "^6.5.0",
    "chai": "^3.5.0",
    "chai-immutable": "^1.5.3",
    "enzyme": "^2.1.0",
    "mocha": "^2.4.5",
    "react": "^0.14.7",
    "react-addons-test-utils": "^0.14.7",
    "react-dom": "^0.14.7",
    "react-native-mock": "0.0.6",
    "redux-devtools": "^3.1.1",
    "sinon": "^1.17.3",
    "slash": "^1.0.0"
  }
}
/* ./test/setup.js */

"use strict";
require("babel-polyfill");

var fs = require('fs');
var path = require('path');

function getBabelRC() {
  var rcpath = path.join(__dirname, '..', '.babelrc');
  var source = fs.readFileSync(rcpath).toString();
  return JSON.parse(source);
}

var config = getBabelRC();

config.ignore = function(filename) {
  if (!(/\/node_modules\//).test(filename)) {

    // if not in node_modules, we want to compile it
    return false; 

  } else if ((/\/node_modules\/react-native\//).test(filename)) {

    // it's RN source code, so we want to compile it
    return false;

  } else {
    // it's in node modules and NOT RN source code
    var modulesToCompileArray = [
      "react-native-button",
      "react-native-router-flux",
      "react-native-tabs",
      "exponent",
      "react-native-clone-referenced-element",
    ];

    for (var i = 0; i < modulesToCompileArray.length; i++) {
      if (filename.includes(modulesToCompileArray[i])) {
        return false;
      }
    }

    return true;
  }
}

require("babel-core/register")(config);

global.__DEV__ = true;

var chai = require('chai');
var chaiImmutable = require('chai-immutable');

global.expect = chai.expect;
chai.use(chaiImmutable);

require("react-native-mock/mock");

This is the error that I get when running the tests.

npm run test

> [email protected] test .../src...
> mocha --require ./test/setup.js --compilers js:babel-core/register 'test/**/*.@(js|jsx)'
.../src.../node_modules/@exponent/react-native-navigator/ExSceneConfigs.js:193
Fade:_reactNative.Navigator.SceneConfigs.FadeAndroid,
                                        ^

TypeError: Cannot read property 'FadeAndroid' of undefined
    at Object.<anonymous> (ExSceneConfigs.js:193:9)
    at Module._compile (module.js:413:34)
    at loader (.../src.../node_modules/babel-core/node_modules/babel-register/lib/node.js:126:5)
    at Object.require.extensions.(anonymous function) [as .js] (.../src.../node_modules/babel-core/node_modules/babel-register/lib/node.js:136:7)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Module.require (module.js:367:17)
    at require (internal/module.js:16:19)
    at Object.<anonymous> (ExRouteRenderer.js:16:1)
    at Module._compile (module.js:413:34)
    at loader (.../src.../node_modules/babel-core/node_modules/babel-register/lib/node.js:126:5)
    at Object.require.extensions.(anonymous function) [as .js] (.../src.../node_modules/babel-core/node_modules/babel-register/lib/node.js:136:7)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Module.require (module.js:367:17)
    at require (internal/module.js:16:19)
    at Object.<anonymous> (ExNavigator.js:16:1)
    at Module._compile (module.js:413:34)
    at loader (.../src.../node_modules/babel-core/node_modules/babel-register/lib/node.js:126:5)
    at Object.require.extensions.(anonymous function) [as .js] (.../src.../node_modules/babel-core/node_modules/babel-register/lib/node.js:136:7)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Module.require (module.js:367:17)
    at require (internal/module.js:16:19)
    at Object.<anonymous> (ExRouter.js:5:1)
    at Module._compile (module.js:413:34)
    at loader (.../src.../node_modules/babel-core/node_modules/babel-register/lib/node.js:126:5)
    at Object.require.extensions.(anonymous function) [as .js] (.../src.../node_modules/babel-core/node_modules/babel-register/lib/node.js:136:7)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Module.require (module.js:367:17)
    at require (internal/module.js:16:19)
    at Object.<anonymous> (Router.js:12:1)
    at Module._compile (module.js:413:34)
    at loader (.../src.../node_modules/babel-core/node_modules/babel-register/lib/node.js:126:5)
    at Object.require.extensions.(anonymous function) [as .js] (.../src.../node_modules/babel-core/node_modules/babel-register/lib/node.js:136:7)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Module.require (module.js:367:17)
    at require (internal/module.js:16:19)
    at Object.<anonymous> (index.js:4:1)
    at Module._compile (module.js:413:34)
    at loader (.../src.../node_modules/babel-core/node_modules/babel-register/lib/node.js:126:5)
    at Object.require.extensions.(anonymous function) [as .js] (.../src.../node_modules/babel-core/node_modules/babel-register/lib/node.js:136:7)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Module.require (module.js:367:17)
    at require (internal/module.js:16:19)
    at Object.<anonymous> (Welcome.js:6:15)
    at Module._compile (module.js:413:34)
    at loader (.../src.../node_modules/babel-core/node_modules/babel-register/lib/node.js:126:5)
    at Object.require.extensions.(anonymous function) [as .js] (.../src.../node_modules/babel-core/node_modules/babel-register/lib/node.js:136:7)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Module.require (module.js:367:17)
    at require (internal/module.js:16:19)
    at Object.<anonymous> (Welcome_spec.js:5:1)
    at Module._compile (module.js:413:34)
    at loader (.../src.../node_modules/babel-core/node_modules/babel-register/lib/node.js:126:5)
    at Object.require.extensions.(anonymous function) [as .js] (.../src.../node_modules/babel-core/node_modules/babel-register/lib/node.js:136:7)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Module.require (module.js:367:17)
    at require (internal/module.js:16:19)
    at .../src.../node_modules/mocha/lib/mocha.js:219:27
    at Array.forEach (native)
    at Mocha.loadFiles (.../src.../node_modules/mocha/lib/mocha.js:216:14)
    at Mocha.run (.../src.../node_modules/mocha/lib/mocha.js:468:10)
    at Object.<anonymous> (.../src.../node_modules/mocha/bin/_mocha:403:18)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Function.Module.runMain (module.js:447:10)
    at startup (node.js:141:18)
    at node.js:933:3

npm ERR! Darwin 15.3.0
npm ERR! argv "/Users/noobs/.nvm/versions/node/v5.7.1/bin/node" "/Users/noobs/.nvm/versions/node/v5.7.1/bin/npm" "run" "test"
npm ERR! node v5.7.1
npm ERR! npm  v3.6.0
npm ERR! code ELIFECYCLE
npm ERR! [email protected] test: `mocha --require ./test/setup.js --compilers js:babel-core/register 'test/**/*.@(js|jsx)'`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] test script 'mocha --require ./test/setup.js --compilers js:babel-core/register 'test/**/*.@(js|jsx)''.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the TestApp package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     mocha --require ./test/setup.js --compilers js:babel-core/register 'test/**/*.@(js|jsx)'
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs TestApp
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls TestApp
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     .../src.../npm-debug.log

Cannot find module 'buildStyleInterpolator'

Hey there! Thanks for all your hard work mocking this all out.

In my app I'm using buildStyleInterpolator which is provided by React Native and made available via import buildStyleInterpolator from 'buildStyleInterpolator'... which I feel is a bit strange in the first place as most library utilities like Dimensions are imported like import {Utility} from 'react-native'.

Regardless, it looks like react-native-mock is not mocking out buildStyleInterpolator as well as various other utility functions that are exported from react-native/Libraries/Utilities/** (screenshot below from my node_modules).

image

Please help me out? (I'll take a look now to see if I can't create a PR myself)
images-1

babel plugin was renamed

Runtime Error
ReferenceError: Unknown plugin "transform-es2015-constants" specified in "/**/node_modules/react-native-mock/.babelrc" at 8, attempted to resolve relative to "/**/node_modules/react-native-mock"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.