react-native-mock icon indicating copy to clipboard operation
react-native-mock copied to clipboard

StyleSheet.create() should return numbers instead of styles itself

Open vitalets opened this issue 9 years ago • 4 comments

create: (obj) => {
      return Object.keys(obj).reduce((res, key, index) => {
        res[key] = index;
        return res;
      }, {})
    }

vitalets avatar Feb 02 '16 09:02 vitalets

@vitalets while this is true, I intentionally chose to make this function return a merged object. This allows tests to assert on the flattened style values, rather than trying to figure it out from the numbers etc.

lelandrichardson avatar Feb 06 '16 03:02 lelandrichardson

ok, I got your point.

vitalets avatar Feb 07 '16 17:02 vitalets

I'm currently working on something where I would like to test some functionality where StyleSheet.create works as it does in react-native. The solution I've come to is to write my own version of mock.js where I monkey patch StyleSheet.create.

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

ReactNativeMock.StyleSheet.create = function create(obj) {
  return Object.keys(obj).reduce((res, key, index) => {
    // eslint-disable-next-line no-param-reassign
    res[key] = index;
    return res;
  }, {});
};

// the cache key that real react native would get
const key = require.resolve('react-native');

// make sure the cache is filled with our lib
require.cache[key] = {
  id: key,
  filename: key,
  loaded: true,
  exports: ReactNativeMock,
};

It might be nice to offer this as an option, or maybe export ReactNativeMock from mock.js in order to enable customizations like this.

lencioni avatar Aug 29 '16 19:08 lencioni

That looks like an alright solution. Especially as it allows not only the types to be valid as with react-native (numbers as keys), but we can also work out the numbers ourselves to assert it's working! Fancy submitting it as a PR @lencioni?

RealOrangeOne avatar Aug 30 '16 08:08 RealOrangeOne