GithubHelp home page GithubHelp logo

react-native-mock-render's Introduction

react-native-mock-render

A fork of react-native-mock that renders components

Requirements

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

Installation

npm i react-native-mock-render --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-render/mock'); // <-- side-effects!!!

Jest

Jest doesn't support require.cache, so the correct way to do the mocking is using jest.mock('react-native', () => require('react-native-mock-render'), {virtual: true}) in your tests setup file.

Why?

We wanted to be able deeply render React Native components in our integration tests and already used react-native-mock.

Contributors

react-native-mock Core Contributors

react-native-mock-render's People

Contributors

arian avatar atareshawty avatar bob-carson avatar c-meek avatar deecewan avatar dingbat avatar feyy avatar gitter-badger avatar isaacsmith13 avatar ivanbtrujillo avatar jacek-rzrz avatar jeiwan avatar joemckie avatar kylekthompson avatar lelandrichardson avatar lulutia avatar mbutsko avatar mcgloneleviroot avatar mroswald avatar omniwheel avatar p16 avatar pbcoronel avatar piranna avatar realorangeone avatar root-devs avatar sibelius avatar stephenh avatar tagraves 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

Watchers

 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

react-native-mock-render's Issues

Creating Custom Mocks

If a mock is not available such as ToastAndroid or you want to use a custom mock of your own, Is there a way to modify a mock or create your own custom mock if not available

A lot of warnings

Hi guys, keeping to implement your fantastic solution but still with problems.

Everytime I test through mount() I receive a list of warnings like this:

console.error node_modules/fbjs/lib/warning.js:33
    Warning: <View /> is using uppercase HTML. Always use lowercase HTML tags in React.

console.error node_modules/fbjs/lib/warning.js:33
    Warning: The tag <View> is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter.

console.error node_modules/fbjs/lib/warning.js:33
    Warning: Stateless function components cannot be given refs. Attempts to access this ref will fail.
    
    Check the render method of `Switch`.
        in Unknown (created by Switch)
        in Switch (created by Filter)
        in View (created by View)
        [...]

console.error node_modules/fbjs/lib/warning.js:33
    Warning: Unknown event handler property `onStartShouldSetResponder`. It will be ignored.
        in RCTSwitch
        in Unknown (created by Switch)
        in Switch (created by Filter)
        [...]

Does somebody have the same problem?

Thanks!

Where are the tags for the latest versions?

I can see multiple versions published on npmjs but I've no idea what fixes are in them (such as the recent Art fix, or even if it was published). The last time something was tagged was 0.0.2.
Where can I find the tags/source revisions for the published builds, i.e. 0.1.9 as of writing?
Thanks!

Mock Touchable.js also please.

I'm using your mock to drive unit tests for react-native components and got problems lately with react-native-svg not finding the touchable mixins. Could you please also support the plain Touchable class.

Cannot find module 'art/core/path.js'.

Following a basic setup, I get the following error running on Jest 22:

 FAIL  frontend/native/screens/__tests__/concentration_screen_spec.js
  ● Test suite failed to run

    Cannot find module 'art/core/class.js' from 'Path.js'

      at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:169:17)
      at Object.<anonymous> (node_modules/react-native-mock-render/build/components/ART/Path.js:1:104)

Searching around in the codebase, I don't see any files that match art/core/class.js. I've had to comment out the ART component in react-native.js on line 13.

Anyone know what's going on there?

Enzyme output

In my unit tests, I used to render the components using the Enzyme shallow() function. The output printed by debug() looked like a regular tree component:

<TouchableOpacity accessibilityComponentType="button">
   <View style={{...}} onLayout={[Function: bound onViewLayout]}>
      <Image source={{...}} style={{...}} />
   </View>
</Component>

Using react-native-mock-render and jsdom, the tree nodes are not named anymore:

<Component accessibilityComponentType="button">
   <Component style={{...}} onLayout={[Function: bound onViewLayout]}>
      <Image source={{...}} style={{...}} />
   </Component>
</Component>

Is it intentional and how can I retrieve each node using the find() function in this case?

src/api/Animated/AnimatedImplementation.js doesn't export delay

const AnimatedImplementation = {
  Value: AnimatedValue,
  ValueXY: AnimatedValueXY,
  decay,
  timing,
  spring,
  subtract,
  add,
  multiply,
  sequence,
  parallel,
  stagger,
  event,

  ...testingMethods,
  __PropsOnlyForTests: AnimatedProps,
  __Animated: Animated,
  __Animation: Animation,
  __AnimatedWithChildren: AnimatedWithChildren,
  __AnimatedStyle: AnimatedStyle,
};

There should be delay function also

I can't simulate an event

Hi guys!

I'm trying to simulate the event onValueChange from Switch but I receive this when I use mount() (shallow is working):

TypeError: ReactWrapper::simulate() event 'valueChange' does not exist

And this is what I wrote:

const filter = wrapper.find(Filter).at(itemIndex)
filter.find('Switch').simulate('valueChange') 

Any idea?

Many thanks!

Mock not working

On Node.js v8.9.1, seems that require.cache is per module and mock.js script side effects are not working. I've done some traces both on mock.js and my setupTests.js file (that calls the first one) and they are different:

  console.log node_modules/react-native-mock-render/mock.js:13
    { '/home/piranna/Trabajo/Quantum/flowtag_react/node_modules/react-native/Libraries/react-native/react-native-implementation.js': 
       { id: '/home/piranna/Trabajo/Quantum/flowtag_react/node_modules/react-native/Libraries/react-native/react-native-implementation.js',
         filename: '/home/piranna/Trabajo/Quantum/flowtag_react/node_modules/react-native/Libraries/react-native/react-native-implementation.js',
         loaded: true,
         exports: 
          { ActivityIndicator: [Object],
            ActivityIndicatorIOS: [Object],
            ART: [Object],
            Button: [Object],
            DatePickerIOS: [Object],
            DrawerLayoutAndroid: [Object],
            Image: [Object],
            ImageBackground: [Object],
            ImageEditor: [Object],
            ImageStore: [Object],
            KeyboardAvoidingView: [Object],
            ListView: [Object],
            MapView: [Object],
            Modal: [Object],
            Navigator: [Object],
            NavigatorIOS: [Object],
            Picker: [Object],
            PickerIOS: [Object],
            ProgressBarAndroid: [Object],
            ProgressViewIOS: [Object],
            ScrollView: [Object],
            SegmentedControlIOS: [Object],
            SliderIOS: [Object],
            SnapshotViewIOS: [Object],
            Switch: [Object],
            PullToRefreshViewAndroid: [Object],
            RecyclerViewBackedScrollView: [Object],
            RefreshControl: [Object],
            StatusBar: [Object],
            SwitchAndroid: [Object],
            SwitchIOS: [Object],
            TabBarIOS: [Object],
            Text: [Object],
            TextInput: [Object],
            ToastAndroid: [Object],
            ToolbarAndroid: [Object],
            Touchable: [Object],
            TouchableHighlight: [Object],
            TouchableNativeFeedback: [Object],
            TouchableOpacity: [Object],
            TouchableWithoutFeedback: [Object],
            View: [Object],
            ViewPagerAndroid: [Object],
            WebView: [Object],
            ActionSheetIOS: [Object],
            Alert: [Object],
            AlertIOS: [Function: AlertIOS],
            Animated: [Object],
            AppRegistry: [Object],
            AppState: [Object],
            AppStateIOS: [Object],
            AsyncStorage: [Object],
            BackAndroid: [Object],
            BackHandler: [Object],
            CameraRoll: [Object],
            Clipboard: [Object],
            DatePickerAndroid: [Function: DatePickerAndroid],
            Dimensions: [Object],
            Easing: [Function: Easing],
            ImagePickerIOS: [Object],
            IntentAndroid: [Function: IntentAndroid],
            InteractionManager: [Object],
            Keyboard: [Object],
            LayoutAnimation: [Object],
            Linking: [Function: Linking],
            LinkingIOS: [Function: LinkingIOS],
            NetInfo: [Object],
            PanResponder: [Object],
            PixelRatio: [Object],
            PushNotificationIOS: [Function: PushNotificationIOS],
            Settings: [Object],
            StatusBarIOS: [Object],
            StyleSheet: [Object],
            TimePickerAndroid: [Function: TimePickerAndroid],
            UIManager: [Object],
            VibrationIOS: [Object],
            DeviceEventEmitter: [Object],
            NativeAppEventEmitter: [Object],
            NativeEventEmitter: [Function: NativeEventEmitter],
            NativeModules: [Object],
            Platform: [Object],
            processColor: [Function: processColor],
            requireNativeComponent: [Function: requireNativeComponent],
            ColorPropType: [Function: ColorPropType],
            EdgeInsetsPropType: [Object],
            PointPropType: [Object],
            NavigationExperimental: [Object],
            ViewPropTypes: [Object],
            Children: [Object],
            Component: [Function: Component],
            PureComponent: [Function: PureComponent],
            unstable_AsyncComponent: [Function: AsyncComponent],
            createElement: [Function: createElementWithValidation],
            cloneElement: [Function: cloneElementWithValidation],
            createFactory: [Function: createFactoryWithValidation],
            isValidElement: [Function: isValidElement],
            version: '16.1.1',
            __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: [Object],
            addons: [Object] } } }
  console.log src/setupTests.js:25
    {}

Am I doing something terrible wrong, or effectively require.cache now is per-module?

Linter errors after upgradind dependencies

I've upgraded project dependencies and it shows a lot of linting errors, probably due to the update of the elint-config-airbnb dependency from 9.0.1 to 16.1.0. When reverting to the currently ones defined on package.json, tests pass successfully.

How to test disabled property?

I'd like to test if my <TouchableOpacity /> is actually disabled but I don't know how.
I'm aware of how to test props but in case of a "disabled" prop, I don't really want to test if the prop is passed but if the button is actually disabled.

How could I do that?

With a React component I would do

const wrapper = mount(
  <Button disabled>
    Title
  </Button>,
);
expect(
  wrapper
    .find('button')
    .getDOMNode()
    .disabled,
).to.be.true;

but I can't find a way to test a react-native component.

Thanks!

Breaks jest-expo

When using jest-expo as a preset for Jest (I'm working on a detached Expo project, jic) and then trying to use react-native-mock-render by adding this line to my Jest config file:

jest.mock('react-native', () => require('react-native-mock-render'), { virtual: true });

This error occurs when running my tests:

The Expo SDK requires Expo to run. It appears the native Expo modules are unavailable and this code is not running on Expo.

The failing check is at node_modules/expo/src/environment/validate.js:

if (!NativeModules.ExponentConstants) {
  throw new Error(ERROR_PASTED_ABOVE);
}

I believe this happens because both libraries are mocking react-native in a non-Object.assign(rn, rn1, rn2)-form.

Couldn't both libraries work together somehow? I believe this would allow things like mounting (as opposed to shallowing) with enzyme, jsdom, and react-native-mock-render on test suites.

Stylesheet.absoluteFill and StyleSheet.absoluteFill

When you have an style like

inactiveBox: {
    ...StyleSheet.absoluteFillObject,
  },

It doesn't render

"position":"absolute",
"right":0,
"left":0,
"top":0,
"bottom":0,
```

Also Stylesheet.absoluteFill is `undefined`

FlatList keyExtractor

Hello there! Congratulations for creating this amazing code. It is very useful.

I'm using FlatList with a keyExtrator prop, that provide an automatic key to the rendered items.

Like this:

<FlatList
  data={this.state.itens}
  removeClippedSubviews={false}
  keyExtractor={(item, index) => index.toString()}
  renderItem={({ item }) => <CustomComponent item={item} removerItem={this.removerItem} />}
/>

But I got the error bellow:

    console.error node_modules/fbjs/lib/warning.js:33
        Warning: Each child in an array or iterator should have a unique "key" prop.

    Check the render method of `FlatList`. See https://fb.me/react-warning-keys for more information.
        in ItemDespensa (created by FlatList)
        in FlatList (created by ListaDespensa)
        in react-native-mock (created by ScrollView)
        in ScrollView (created by ListaDespensa)
        in react-native-mock (created by View)
        in View (created by ListaDespensa)
        in ListaDespensa (created by WrapperComponent)
        in WrapperComponent

Would you have any solution about this?

Thanks!

Need to update react-dom to the latest version

I got this error when I run storybook on my react-native app:

ERROR in ./~/react-dom/lib/ReactMount.js
Module not found: Error: Can't resolve 'react/lib/React' in '/Users/hungvo/Projects/songnhi/react-native/node_modules/react-dom/lib'
 @ ./~/react-dom/lib/ReactMount.js 17:12-38
 @ ./~/react-dom/lib/ReactDOM.js
 @ ./~/react-dom/index.js
 @ ./~/react-modal/lib/components/Modal.js
 @ ./~/react-modal/lib/index.js
 @ ./~/@storybook/ui/dist/modules/ui/components/shortcuts_help.js
 @ ./~/@storybook/ui/dist/modules/ui/containers/shortcuts_help.js
 @ ./~/@storybook/ui/dist/modules/ui/routes.js
 @ ./~/@storybook/ui/dist/modules/ui/index.js
 @ ./~/@storybook/ui/dist/index.js
 @ ./~/@storybook/react-native/dist/manager/index.js
 @ multi ./storybook/addons.js ./~/@storybook/react-native/dist/manager/index.js

It is solved after I remove react-native-mock-render. Turns out the problem was that react-native-mock-render uses [email protected]. Remove it and use [email protected] works

yarn list v0.27.5
└─ [email protected]
   └─ [email protected]

Setup problems

Thanks a lot for your library. I think this is exactly what I have been looking for. I also had the problem you are describeing in your blog post that using shallow rendering is often not sufficient for testing RN components.

I tried using your library but unfortunately I wasn't able to get it to work (yet).

I think I have a pretty standard jest+RN setup, but I wouldn't know what (or where) my file-that-runs-before-all-of-my-tests.js could be.

I tried just inserting the require('react-native-mock-render/mock') into my individual component test, but that simply led to issues such as

console.error node_modules/react-native/Libraries/Core/ExceptionsManager.js:71
    Warning: Unknown props `keyboardType`, `secureTextEntry`, `underlineColorAndroid`, `selectionColor`, `onChangeText`, `multiline`, `numberOfLines`, `blurOnSubmit`, `onSubmitEditing`, `returnKeyType` on <TextInput> tag. Remove these props from the element. For details, see https://fb.me/react-unknown-prop

Seem like this is not coming from the mock implementation. Do you happen to have any idea for me how to properly require your library when using jest?


Before that I also had the error message ReferenceError: document is not defined but that was solved by adding

import {jsdom} from 'jsdom'

global.document = jsdom('')
global.window = document.defaultView
Object.keys(document.defaultView).forEach((property) => {
  if (typeof global[property] === 'undefined') {
    global[property] = document.defaultView[property]
  }
})

Just as you are describing in your blog post. I think it would be very good to also add this to the README of this library.

Unexpected duplicate nested components

When I mount() some components, they end up having nested duplicates.

For example,

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

import { mount } from 'enzyme';

describe('component', () => {
	it('renders', () => {
		console.log(mount(<View />).debug());
	});
});

Here's what I see in the log:

  console.log /__tests__/test.js:44
    <View>
      <View />
    </View>

I see this behavior with View, Text, ActivityIndicator, but not with TouchableOpacity or custom components. Finding components becomes much more complicated.

What might be going on here? Is this behavior expected or is it a bug?

Mock still requires adapter

When attempting to add require('react-native-mock-render/mock'); to my project to mock out the react native implementation I'm faced with an Enzyme Internal Error: Enzyme expects an adapter to be configured, but found none.

I've attempted to setup the JSDOM as such:

require('react-native-mock-render/mock');

const { JSDOM } = require('jsdom');

const jsdom = new JSDOM('');
const { window } = jsdom;
const { document } = window;

global.document = document;
global.window = document.defaultView;
global.navigator = {
  userAgent: 'node.js',
};

Object.keys(document.defaultView).forEach((property) => {
  if (global[property] === 'undefined') {
    global[property] = document.defaultView[property];
  }
});

Although I'm not 100% sure that this is the correct setup for getting the adapter to work.

Edit:

Updated the code to match with JSDOM +10 and from the airbnb documentation:

require('react-native-mock-render/mock');

const { JSDOM } = require('jsdom');

const jsdom = new JSDOM('<!doctype html><html><body></body></html>');
const { window } = jsdom;

function copyProps(src, target) {
  const props = Object.getOwnPropertyNames(src)
    .filter(prop => typeof target[prop] === 'undefined')
    .reduce((result, prop) => ({
      ...result,
      [prop]: Object.getOwnPropertyDescriptor(src, prop),
    }), {});
  Object.defineProperties(target, props);
}

global.window = window;
global.document = window.document;
global.navigator = {
  userAgent: 'node.js',
};
copyProps(window, global);

Same error however.

What's the mechanism to use it with latest react native version?

We are using react-native: "0.55.4" which > the react-native version used this module and thus not finding the latest components like . What is the recommended approach to make new components available?

Running this error when using

Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
      

How to use `Platform.__setOS()`?

When using components that has several implementations for different platforms (for example with .android.js or .web.js extensions), ReactNative uses Platform.OS to identify the current platform. react-native-mock-render is using by default ios, so my tests are failing. It adds a Platform.__setOS() private method to select the platform to be emulated, but I'm not able to use it on my code and there's no examples about how to do it. Could you be able to give me some advice about that?

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.