Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change isPlainObject to support objects created in a different context #3068

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 7 additions & 1 deletion packages/styled-components/src/utils/isPlainObject.js
@@ -1,2 +1,8 @@
// @flow
export default (x: any): boolean => typeof x === 'object' && x.constructor === Object;
import { typeOf } from 'react-is';

export default (x: any): boolean =>
x !== null &&
typeof x === 'object' &&
(x.toString ? x.toString() : Object.prototype.toString.call(x)) === '[object Object]' &&
!typeOf(x);
36 changes: 36 additions & 0 deletions packages/styled-components/src/utils/test/isPlainObject.test.js
@@ -0,0 +1,36 @@
// @flow
import vm from "vm";
import React from "react";
import isPlainObject from '../isPlainObject';

it('returns true for an object literal', () => {
expect(isPlainObject({})).toEqual(true);
});

it('returns false for an instance of a class with its own toString method', () => {
class SomeClass {
toString() {
return 'some: thing;';
}
}
expect(isPlainObject(new SomeClass())).toEqual(false);
});

it('returns false for a function', () => {
expect(isPlainObject(() => {})).toEqual(false);
});

it('returns false for an array', () => {
expect(isPlainObject([])).toEqual(false);
});

it('returns false for a React component', () => {
class Foo extends React.Component {};
expect(isPlainObject(Foo)).toEqual(false);
});

it('returns true for an object literal created in a different context', () => {
const context = vm.createContext({});
vm.runInContext('object = {};', context);
expect(isPlainObject(context.object)).toEqual(true);
});