. See ' +
- 'https://fb.me/react-warning-keys for more information.'
+ 'https://fb.me/react-warning-keys for more information.\n' +
+ ' in div (at **)'
+ );
+ });
+
+ it('warns for keys with component stack info', function() {
+ spyOn(console, 'error');
+
+ var Component = React.createClass({
+ render: function() {
+ return
;
+ },
+ });
+
+ var Parent = React.createClass({
+ render: function() {
+ return React.cloneElement(this.props.child);
+ },
+ });
+
+ var GrandParent = React.createClass({
+ render: function() {
+ return
} />;
+ },
+ });
+
+ ReactTestUtils.renderIntoDocument(
);
+
+ expect(console.error.calls.count()).toBe(1);
+ expect(normalizeCodeLocInfo(console.error.calls.argsFor(0)[0])).toBe(
+ 'Warning: Each child in an array or iterator should have a unique ' +
+ '"key" prop. Check the render method of `Component`. See ' +
+ 'https://fb.me/react-warning-keys for more information.\n' +
+ ' in div (at **)\n' +
+ ' in Component (at **)\n' +
+ ' in Parent (at **)\n' +
+ ' in GrandParent (at **)'
);
});
@@ -139,7 +180,7 @@ describe('ReactElementValidator', function() {
);
- expect(console.error.argsForCall.length).toBe(0);
+ expect(console.error.calls.count()).toBe(0);
});
it('warns for keys for iterables of elements in rest args', function() {
@@ -160,8 +201,8 @@ describe('ReactElementValidator', function() {
Component(null, iterable);
- expect(console.error.argsForCall.length).toBe(1);
- expect(console.error.argsForCall[0][0]).toContain(
+ expect(console.error.calls.count()).toBe(1);
+ expect(console.error.calls.argsFor(0)[0]).toContain(
'Each child in an array or iterator should have a unique "key" prop.'
);
});
@@ -172,7 +213,7 @@ describe('ReactElementValidator', function() {
Component(null, [Component({key: '#1'}), Component({key: '#2'})]);
- expect(console.error.argsForCall.length).toBe(0);
+ expect(console.error.calls.count()).toBe(0);
});
it('does not warns for iterable elements with keys', function() {
@@ -196,7 +237,7 @@ describe('ReactElementValidator', function() {
Component(null, iterable);
- expect(console.error.argsForCall.length).toBe(0);
+ expect(console.error.calls.count()).toBe(0);
});
it('does not warn when the element is directly in rest args', function() {
@@ -205,7 +246,7 @@ describe('ReactElementValidator', function() {
Component(null, Component(), Component());
- expect(console.error.argsForCall.length).toBe(0);
+ expect(console.error.calls.count()).toBe(0);
});
it('does not warn when the array contains a non-element', function() {
@@ -214,7 +255,7 @@ describe('ReactElementValidator', function() {
Component(null, [{}, {}]);
- expect(console.error.argsForCall.length).toBe(0);
+ expect(console.error.calls.count()).toBe(0);
});
// TODO: These warnings currently come from the composite component, but
@@ -239,10 +280,12 @@ describe('ReactElementValidator', function() {
},
});
ReactTestUtils.renderIntoDocument(React.createElement(ParentComp));
- expect(console.error.argsForCall[0][0]).toBe(
- 'Warning: Failed propType: ' +
+ expect(console.error.calls.argsFor(0)[0]).toBe(
+ 'Warning: Failed prop type: ' +
'Invalid prop `color` of type `number` supplied to `MyComp`, ' +
- 'expected `string`. Check the render method of `ParentComp`.'
+ 'expected `string`.\n' +
+ ' in MyComp (created by ParentComp)\n' +
+ ' in ParentComp'
);
});
@@ -252,29 +295,29 @@ describe('ReactElementValidator', function() {
React.createElement(null);
React.createElement(true);
React.createElement(123);
- expect(console.error.calls.length).toBe(4);
- expect(console.error.argsForCall[0][0]).toBe(
+ expect(console.error.calls.count()).toBe(4);
+ expect(console.error.calls.argsFor(0)[0]).toBe(
'Warning: React.createElement: type should not be null, undefined, ' +
'boolean, or number. It should be a string (for DOM elements) or a ' +
'ReactClass (for composite components).'
);
- expect(console.error.argsForCall[1][0]).toBe(
+ expect(console.error.calls.argsFor(1)[0]).toBe(
'Warning: React.createElement: type should not be null, undefined, ' +
'boolean, or number. It should be a string (for DOM elements) or a ' +
'ReactClass (for composite components).'
);
- expect(console.error.argsForCall[2][0]).toBe(
+ expect(console.error.calls.argsFor(2)[0]).toBe(
'Warning: React.createElement: type should not be null, undefined, ' +
'boolean, or number. It should be a string (for DOM elements) or a ' +
'ReactClass (for composite components).'
);
- expect(console.error.argsForCall[3][0]).toBe(
+ expect(console.error.calls.argsFor(3)[0]).toBe(
'Warning: React.createElement: type should not be null, undefined, ' +
'boolean, or number. It should be a string (for DOM elements) or a ' +
'ReactClass (for composite components).'
);
React.createElement('div');
- expect(console.error.calls.length).toBe(4);
+ expect(console.error.calls.count()).toBe(4);
});
it('includes the owner name when passing null, undefined, boolean, or number', function() {
@@ -286,13 +329,13 @@ describe('ReactElementValidator', function() {
});
expect(function() {
ReactTestUtils.renderIntoDocument(React.createElement(ParentComp));
- }).toThrow(
+ }).toThrowError(
'Element type is invalid: expected a string (for built-in components) ' +
'or a class/function (for composite components) but got: null. Check ' +
'the render method of `ParentComp`.'
);
- expect(console.error.calls.length).toBe(1);
- expect(console.error.argsForCall[0][0]).toBe(
+ expect(console.error.calls.count()).toBe(1);
+ expect(console.error.calls.argsFor(0)[0]).toBe(
'Warning: React.createElement: type should not be null, undefined, ' +
'boolean, or number. It should be a string (for DOM elements) or a ' +
'ReactClass (for composite components). Check the render method of ' +
@@ -315,10 +358,11 @@ describe('ReactElementValidator', function() {
ReactTestUtils.renderIntoDocument(React.createElement(Component));
- expect(console.error.calls.length).toBe(1);
- expect(console.error.argsForCall[0][0]).toBe(
- 'Warning: Failed propType: ' +
- 'Required prop `prop` was not specified in `Component`.'
+ expect(console.error.calls.count()).toBe(1);
+ expect(console.error.calls.argsFor(0)[0]).toBe(
+ 'Warning: Failed prop type: ' +
+ 'Required prop `prop` was not specified in `Component`.\n' +
+ ' in Component'
);
});
@@ -339,10 +383,11 @@ describe('ReactElementValidator', function() {
React.createElement(Component, {prop:null})
);
- expect(console.error.calls.length).toBe(1);
- expect(console.error.argsForCall[0][0]).toBe(
- 'Warning: Failed propType: ' +
- 'Required prop `prop` was not specified in `Component`.'
+ expect(console.error.calls.count()).toBe(1);
+ expect(console.error.calls.argsFor(0)[0]).toBe(
+ 'Warning: Failed prop type: ' +
+ 'Required prop `prop` was not specified in `Component`.\n' +
+ ' in Component'
);
});
@@ -365,16 +410,18 @@ describe('ReactElementValidator', function() {
React.createElement(Component, {prop: 42})
);
- expect(console.error.calls.length).toBe(2);
- expect(console.error.argsForCall[0][0]).toBe(
- 'Warning: Failed propType: ' +
- 'Required prop `prop` was not specified in `Component`.'
+ expect(console.error.calls.count()).toBe(2);
+ expect(console.error.calls.argsFor(0)[0]).toBe(
+ 'Warning: Failed prop type: ' +
+ 'Required prop `prop` was not specified in `Component`.\n' +
+ ' in Component'
);
- expect(console.error.argsForCall[1][0]).toBe(
- 'Warning: Failed propType: ' +
+ expect(console.error.calls.argsFor(1)[0]).toBe(
+ 'Warning: Failed prop type: ' +
'Invalid prop `prop` of type `number` supplied to ' +
- '`Component`, expected `string`.'
+ '`Component`, expected `string`.\n' +
+ ' in Component'
);
ReactTestUtils.renderIntoDocument(
@@ -382,7 +429,7 @@ describe('ReactElementValidator', function() {
);
// Should not error for strings
- expect(console.error.calls.length).toBe(2);
+ expect(console.error.calls.count()).toBe(2);
});
it('should warn if a PropType creator is used as a PropType', function() {
@@ -401,8 +448,8 @@ describe('ReactElementValidator', function() {
React.createElement(Component, {myProp: {value: 'hi'}})
);
- expect(console.error.calls.length).toBe(1);
- expect(console.error.argsForCall[0][0]).toBe(
+ expect(console.error.calls.count()).toBe(1);
+ expect(console.error.calls.argsFor(0)[0]).toBe(
'Warning: Component: type specification of prop `myProp` is invalid; ' +
'the type checker function must return `null` or an `Error` but ' +
'returned a function. You may have forgotten to pass an argument to ' +
@@ -420,14 +467,14 @@ describe('ReactElementValidator', function() {
});
var TestFactory = React.createFactory(TestComponent);
expect(TestFactory.type).toBe(TestComponent);
- expect(console.error.argsForCall.length).toBe(1);
- expect(console.error.argsForCall[0][0]).toBe(
+ expect(console.error.calls.count()).toBe(1);
+ expect(console.error.calls.argsFor(0)[0]).toBe(
'Warning: Factory.type is deprecated. Access the class directly before ' +
'passing it to createFactory.'
);
// Warn once, not again
expect(TestFactory.type).toBe(TestComponent);
- expect(console.error.argsForCall.length).toBe(1);
+ expect(console.error.calls.count()).toBe(1);
});
it('does not warn when using DOM node as children', function() {
@@ -444,7 +491,7 @@ describe('ReactElementValidator', function() {
var node = document.createElement('div');
// This shouldn't cause a stack overflow or any other problems (#3883)
ReactTestUtils.renderIntoDocument(
{node});
- expect(console.error.argsForCall.length).toBe(0);
+ expect(console.error.calls.count()).toBe(0);
});
it('should not enumerate enumerable numbers (#4776)', function() {
@@ -487,8 +534,8 @@ describe('ReactElementValidator', function() {
spyOn(console, 'error');
var Foo = undefined;
void
{[]};
- expect(console.error.argsForCall.length).toBe(1);
- expect(console.error.argsForCall[0][0]).toBe(
+ expect(console.error.calls.count()).toBe(1);
+ expect(console.error.calls.argsFor(0)[0]).toBe(
'Warning: React.createElement: type should not be null, undefined, ' +
'boolean, or number. It should be a string (for DOM elements) or a ' +
'ReactClass (for composite components).'
diff --git a/src/isomorphic/classic/types/ReactPropTypes.js b/src/isomorphic/classic/types/ReactPropTypes.js
index 99c036496a..4d9ac1d846 100644
--- a/src/isomorphic/classic/types/ReactPropTypes.js
+++ b/src/isomorphic/classic/types/ReactPropTypes.js
@@ -73,6 +73,7 @@ var ReactPropTypes = {
number: createPrimitiveTypeChecker('number'),
object: createPrimitiveTypeChecker('object'),
string: createPrimitiveTypeChecker('string'),
+ symbol: createPrimitiveTypeChecker('symbol'),
any: createAnyTypeChecker(),
arrayOf: createArrayOfTypeChecker,
@@ -406,6 +407,25 @@ function isNode(propValue) {
}
}
+function isSymbol(propType, propValue) {
+ // Native Symbol.
+ if (propType === 'symbol') {
+ return true;
+ }
+
+ // 19.4.3.5 Symbol.prototype[@@toStringTag] === 'Symbol'
+ if (propValue['@@toStringTag'] === 'Symbol') {
+ return true;
+ }
+
+ // Fallback for non-spec compliant Symbols which are polyfilled.
+ if (typeof Symbol === 'function' && propValue instanceof Symbol) {
+ return true;
+ }
+
+ return false;
+}
+
// Equivalent of `typeof` but with special handling for array and regexp.
function getPropType(propValue) {
var propType = typeof propValue;
@@ -418,6 +438,9 @@ function getPropType(propValue) {
// passes PropTypes.object.
return 'object';
}
+ if (isSymbol(propType, propValue)) {
+ return 'symbol';
+ }
return propType;
}
diff --git a/src/isomorphic/classic/types/__tests__/ReactPropTypes-test.js b/src/isomorphic/classic/types/__tests__/ReactPropTypes-test.js
index 9601e675b7..14559720ae 100644
--- a/src/isomorphic/classic/types/__tests__/ReactPropTypes-test.js
+++ b/src/isomorphic/classic/types/__tests__/ReactPropTypes-test.js
@@ -80,6 +80,12 @@ describe('ReactPropTypes', function() {
'Invalid prop `testProp` of type `object` supplied to ' +
'`testComponent`, expected `string`.'
);
+ typeCheckFail(
+ PropTypes.string,
+ Symbol(),
+ 'Invalid prop `testProp` of type `symbol` supplied to ' +
+ '`testComponent`, expected `string`.'
+ );
});
it('should fail date and regexp correctly', function() {
@@ -106,6 +112,7 @@ describe('ReactPropTypes', function() {
typeCheckPass(PropTypes.object, {});
typeCheckPass(PropTypes.object, new Date());
typeCheckPass(PropTypes.object, /please/);
+ typeCheckPass(PropTypes.symbol, Symbol());
});
it('should be implicitly optional and not warn without values', function() {
@@ -124,6 +131,7 @@ describe('ReactPropTypes', function() {
typeCheckPass(PropTypes.any, 0);
typeCheckPass(PropTypes.any, 'str');
typeCheckPass(PropTypes.any, []);
+ typeCheckPass(PropTypes.any, Symbol());
});
it('should be implicitly optional and not warn without values', function() {
@@ -150,6 +158,7 @@ describe('ReactPropTypes', function() {
typeCheckPass(PropTypes.arrayOf(PropTypes.number), [1, 2, 3]);
typeCheckPass(PropTypes.arrayOf(PropTypes.string), ['a', 'b', 'c']);
typeCheckPass(PropTypes.arrayOf(PropTypes.oneOf(['a', 'b'])), ['a', 'b']);
+ typeCheckPass(PropTypes.arrayOf(PropTypes.symbol), [Symbol(), Symbol()]);
});
it('should support arrayOf with complex types', function() {
@@ -262,7 +271,7 @@ describe('ReactPropTypes', function() {
var instance =
} />;
instance = ReactTestUtils.renderIntoDocument(instance);
- expect(console.error.argsForCall.length).toBe(0);
+ expect(console.error.calls.count()).toBe(0);
});
it('should warn when passing no label and isRequired is set', () => {
@@ -271,7 +280,7 @@ describe('ReactPropTypes', function() {
var instance =
;
instance = ReactTestUtils.renderIntoDocument(instance);
- expect(console.error.argsForCall.length).toBe(1);
+ expect(console.error.calls.count()).toBe(1);
});
it('should be implicitly optional and not warn without values', function() {
@@ -412,7 +421,7 @@ describe('ReactPropTypes', function() {
k4: null,
k5: undefined,
}));
- expect(console.error.calls).toEqual([]);
+ expect(console.error.calls.count()).toBe(0);
});
it('should not warn for iterables', function() {
@@ -490,6 +499,10 @@ describe('ReactPropTypes', function() {
PropTypes.objectOf(PropTypes.oneOf(['a', 'b'])),
{a: 'a', b: 'b'}
);
+ typeCheckPass(
+ PropTypes.objectOf(PropTypes.symbol),
+ {a: Symbol(), b: Symbol(), c: Symbol()}
+ );
});
it('should support objectOf with complex types', function() {
@@ -545,6 +558,12 @@ describe('ReactPropTypes', function() {
'Invalid prop `testProp` of type `string` supplied to ' +
'`testComponent`, expected an object.'
);
+ typeCheckFail(
+ PropTypes.objectOf(PropTypes.symbol),
+ Symbol(),
+ 'Invalid prop `testProp` of type `symbol` supplied to ' +
+ '`testComponent`, expected an object.'
+ );
});
it('should not warn when passing an empty object', function() {
@@ -782,6 +801,36 @@ describe('ReactPropTypes', function() {
});
});
+ describe('Symbol Type', function() {
+ it('should warn for non-symbol', function() {
+ typeCheckFail(
+ PropTypes.symbol,
+ 'hello',
+ 'Invalid prop `testProp` of type `string` supplied to ' +
+ '`testComponent`, expected `symbol`.'
+ );
+ typeCheckFail(
+ PropTypes.symbol,
+ function() { },
+ 'Invalid prop `testProp` of type `function` supplied to ' +
+ '`testComponent`, expected `symbol`.'
+ );
+ typeCheckFail(
+ PropTypes.symbol,
+ {
+ '@@toStringTag': 'Katana',
+ },
+ 'Invalid prop `testProp` of type `object` supplied to ' +
+ '`testComponent`, expected `symbol`.'
+ );
+ });
+
+ it('should not warn for a polyfilled Symbol', function() {
+ var CoreSymbol = require('core-js/library/es6/symbol');
+ typeCheckPass(PropTypes.symbol, CoreSymbol('core-js'));
+ });
+ });
+
describe('Custom validator', function() {
beforeEach(function() {
jest.resetModuleRegistry();
@@ -800,9 +849,8 @@ describe('ReactPropTypes', function() {
var instance =
;
instance = ReactTestUtils.renderIntoDocument(instance);
- expect(spy.argsForCall.length).toBe(2); // temp double validation
- expect(spy.argsForCall[0][1]).toBe('num');
- expect(spy.argsForCall[0][2]).toBe('Component');
+ expect(spy.calls.count()).toBe(1);
+ expect(spy.calls.argsFor(0)[1]).toBe('num');
});
it('should have been called even if the prop is not present', function() {
@@ -818,13 +866,13 @@ describe('ReactPropTypes', function() {
var instance =
;
instance = ReactTestUtils.renderIntoDocument(instance);
- expect(spy.argsForCall.length).toBe(2); // temp double validation
+ expect(spy.calls.count()).toBe(1);
+ expect(spy.calls.argsFor(0)[1]).toBe('num');
});
it('should have received the validator\'s return value', function() {
spyOn(console, 'error');
-
- var spy = jasmine.createSpy().andCallFake(
+ var spy = jasmine.createSpy().and.callFake(
function(props, propName, componentName) {
if (props[propName] !== 5) {
return new Error('num must be 5!');
@@ -841,17 +889,19 @@ describe('ReactPropTypes', function() {
var instance =
;
instance = ReactTestUtils.renderIntoDocument(instance);
- expect(console.error.argsForCall.length).toBe(1);
- expect(console.error.argsForCall[0][0]).toBe(
- 'Warning: Failed propType: num must be 5!'
+ expect(console.error.calls.count()).toBe(1);
+ expect(
+ console.error.calls.argsFor(0)[0].replace(/\(at .+?:\d+\)/g, '(at **)')
+ ).toBe(
+ 'Warning: Failed prop type: num must be 5!\n' +
+ ' in Component (at **)'
);
});
it('should not warn if the validator returned null',
function() {
spyOn(console, 'error');
-
- var spy = jasmine.createSpy().andCallFake(
+ var spy = jasmine.createSpy().and.callFake(
function(props, propName, componentName) {
return null;
}
@@ -866,7 +916,7 @@ describe('ReactPropTypes', function() {
var instance =
;
instance = ReactTestUtils.renderIntoDocument(instance);
- expect(console.error.argsForCall.length).toBe(0);
+ expect(console.error.calls.count()).toBe(0);
}
);
});
diff --git a/src/isomorphic/classic/types/checkReactTypeSpec.js b/src/isomorphic/classic/types/checkReactTypeSpec.js
new file mode 100644
index 0000000000..3b119b395f
--- /dev/null
+++ b/src/isomorphic/classic/types/checkReactTypeSpec.js
@@ -0,0 +1,93 @@
+/**
+ * Copyright 2013-present, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule checkReactTypeSpec
+ */
+
+'use strict';
+
+var ReactComponentTreeDevtool = require('ReactComponentTreeDevtool');
+var ReactPropTypeLocationNames = require('ReactPropTypeLocationNames');
+
+var invariant = require('invariant');
+var warning = require('warning');
+
+var loggedTypeFailures = {};
+
+/**
+ * Assert that the values match with the type specs.
+ * Error messages are memorized and will only be shown once.
+ *
+ * @param {object} typeSpecs Map of name to a ReactPropType
+ * @param {object} values Runtime values that need to be type-checked
+ * @param {string} location e.g. "prop", "context", "child context"
+ * @param {string} componentName Name of the component for error messages.
+ * @param {?object} element The React element that is being type-checked
+ * @param {?number} debugID The React component instance that is being type-checked
+ * @private
+ */
+function checkReactTypeSpec(typeSpecs, values, location, componentName, element, debugID) {
+ for (var typeSpecName in typeSpecs) {
+ if (typeSpecs.hasOwnProperty(typeSpecName)) {
+ var error;
+ // Prop type validation may throw. In case they do, we don't want to
+ // fail the render phase where it didn't fail before. So we log it.
+ // After these have been cleaned up, we'll let them throw.
+ try {
+ // This is intentionally an invariant that gets caught. It's the same
+ // behavior as without this statement except with a better message.
+ invariant(
+ typeof typeSpecs[typeSpecName] === 'function',
+ '%s: %s type `%s` is invalid; it must be a function, usually from ' +
+ 'React.PropTypes.',
+ componentName || 'React class',
+ ReactPropTypeLocationNames[location],
+ typeSpecName
+ );
+ error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location);
+ } catch (ex) {
+ error = ex;
+ }
+ warning(
+ !error || error instanceof Error,
+ '%s: type specification of %s `%s` is invalid; the type checker ' +
+ 'function must return `null` or an `Error` but returned a %s. ' +
+ 'You may have forgotten to pass an argument to the type checker ' +
+ 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' +
+ 'shape all require an argument).',
+ componentName || 'React class',
+ ReactPropTypeLocationNames[location],
+ typeSpecName,
+ typeof error
+ );
+ if (error instanceof Error && !(error.message in loggedTypeFailures)) {
+ // Only monitor this failure once because there tends to be a lot of the
+ // same error.
+ loggedTypeFailures[error.message] = true;
+
+ var componentStackInfo = '';
+
+ if (debugID !== null) {
+ componentStackInfo = ReactComponentTreeDevtool.getStackAddendumByID(debugID);
+ } else if (element !== null) {
+ componentStackInfo = ReactComponentTreeDevtool.getCurrentStackAddendum(element);
+ }
+
+ warning(
+ false,
+ 'Failed %s type: %s%s',
+ location,
+ error.message,
+ componentStackInfo
+ );
+ }
+ }
+ }
+}
+
+module.exports = checkReactTypeSpec;
diff --git a/src/isomorphic/modern/class/ReactComponent.js b/src/isomorphic/modern/class/ReactComponent.js
index a775abd67d..b93da63e94 100644
--- a/src/isomorphic/modern/class/ReactComponent.js
+++ b/src/isomorphic/modern/class/ReactComponent.js
@@ -12,7 +12,6 @@
'use strict';
var ReactNoopUpdateQueue = require('ReactNoopUpdateQueue');
-var ReactInstrumentation = require('ReactInstrumentation');
var canDefineProperty = require('canDefineProperty');
var emptyObject = require('emptyObject');
@@ -66,14 +65,6 @@ ReactComponent.prototype.setState = function(partialState, callback) {
'setState(...): takes an object of state variables to update or a ' +
'function which returns an object of state variables.'
);
- if (__DEV__) {
- ReactInstrumentation.debugTool.onSetState();
- warning(
- partialState != null,
- 'setState(...): You passed an undefined or null state object; ' +
- 'instead, use forceUpdate().'
- );
- }
this.updater.enqueueSetState(this, partialState);
if (callback) {
this.updater.enqueueCallback(this, callback, 'setState');
diff --git a/src/isomorphic/modern/class/__tests__/ReactClassEquivalence-test.js b/src/isomorphic/modern/class/__tests__/ReactClassEquivalence-test.js
index 36cf5c75ce..0d91c3a144 100644
--- a/src/isomorphic/modern/class/__tests__/ReactClassEquivalence-test.js
+++ b/src/isomorphic/modern/class/__tests__/ReactClassEquivalence-test.js
@@ -11,24 +11,62 @@
'use strict';
-var MetaMatchers = require('MetaMatchers');
+var spawnSync = require('child_process').spawnSync;
+var path = require('path');
describe('ReactClassEquivalence', function() {
-
- beforeEach(function() {
- this.addMatchers(MetaMatchers);
- });
-
- var es6 = () => require('./ReactES6Class-test.js');
- var coffee = () => require('./ReactCoffeeScriptClass-test.coffee');
- var ts = () => require('./ReactTypeScriptClass-test.ts');
-
it('tests the same thing for es6 classes and CoffeeScript', function() {
- expect(coffee).toEqualSpecsIn(es6);
+ var result1 = runJest('ReactCoffeeScriptClass-test.coffee');
+ var result2 = runJest('ReactES6Class-test.js');
+ compareResults(result1, result2);
});
it('tests the same thing for es6 classes and TypeScript', function() {
- expect(ts).toEqualSpecsIn(es6);
+ var result1 = runJest('ReactTypeScriptClass-test.ts');
+ var result2 = runJest('ReactES6Class-test.js');
+ compareResults(result1, result2);
});
});
+
+function runJest(testFile) {
+ var cwd = process.cwd();
+ var jestBin = path.resolve('node_modules', '.bin', 'jest');
+ var setupFile = path.resolve(__dirname, 'setupSpecEquivalenceReporter.js');
+ var result = spawnSync('node', [
+ jestBin,
+ testFile,
+ '--setupTestFrameworkScriptFile',
+ setupFile,
+ ], {cwd});
+
+ if (result.error) {
+ throw result.error;
+ }
+
+ if (result.status !== 0) {
+ throw new Error(
+ 'jest process exited with: ' +
+ result.status +
+ '\n' +
+ 'stdout: ' +
+ result.stdout.toString() +
+ 'stderr: ' +
+ result.stderr.toString()
+ );
+ }
+
+ return result.stdout.toString();
+}
+
+function compareResults(a, b) {
+ var regexp = /^EQUIVALENCE.*$/gm;
+ var aSpecs = (a.match(regexp) || []).sort().join('\n');
+ var bSpecs = (b.match(regexp) || []).sort().join('\n');
+
+ if (aSpecs.length === 0 && bSpecs.length === 0) {
+ throw new Error('No spec results found in the output');
+ }
+
+ expect(aSpecs).toEqual(bSpecs);
+}
diff --git a/src/isomorphic/modern/class/__tests__/ReactCoffeeScriptClass-test.coffee b/src/isomorphic/modern/class/__tests__/ReactCoffeeScriptClass-test.coffee
index e7b1f574c5..a9871ea6ba 100644
--- a/src/isomorphic/modern/class/__tests__/ReactCoffeeScriptClass-test.coffee
+++ b/src/isomorphic/modern/class/__tests__/ReactCoffeeScriptClass-test.coffee
@@ -51,8 +51,9 @@ describe 'ReactCoffeeScriptClass', ->
expect(->
ReactDOM.render React.createElement(Foo), container
).toThrow()
- expect(console.error.calls.length).toBe(1)
- expect(console.error.argsForCall[0][0]).toContain('No `render` method found on the returned component instance')
+ expect(console.error.calls.count()).toBe(1)
+ expect(console.error.calls.argsFor(0)[0]).toContain('No `render` method found on the returned component instance')
+ undefined
it 'renders a simple stateless component with prop', ->
class Foo extends React.Component
@@ -62,6 +63,7 @@ describe 'ReactCoffeeScriptClass', ->
test React.createElement(Foo, bar: 'foo'), 'DIV', 'foo'
test React.createElement(Foo, bar: 'bar'), 'DIV', 'bar'
+ undefined
it 'renders based on state using initial values in this.props', ->
class Foo extends React.Component
@@ -74,6 +76,7 @@ describe 'ReactCoffeeScriptClass', ->
className: @state.bar
test React.createElement(Foo, initialValue: 'foo'), 'SPAN', 'foo'
+ undefined
it 'renders based on state using props in the constructor', ->
class Foo extends React.Component
@@ -94,6 +97,7 @@ describe 'ReactCoffeeScriptClass', ->
instance = test React.createElement(Foo, initialValue: 'foo'), 'DIV', 'foo'
instance.changeState()
test React.createElement(Foo), 'SPAN', 'bar'
+ undefined
it 'renders based on context in the constructor', ->
class Foo extends React.Component
@@ -125,6 +129,7 @@ describe 'ReactCoffeeScriptClass', ->
React.createElement Foo
test React.createElement(Outer), 'SPAN', 'foo'
+ undefined
it 'renders only once when setting state in componentWillMount', ->
renderCount = 0
@@ -141,6 +146,7 @@ describe 'ReactCoffeeScriptClass', ->
test React.createElement(Foo, initialValue: 'foo'), 'SPAN', 'bar'
expect(renderCount).toBe 1
+ undefined
it 'should throw with non-object in the initial state property', ->
[['an array'], 'a string', 1234].forEach (state) ->
@@ -153,9 +159,10 @@ describe 'ReactCoffeeScriptClass', ->
expect(->
test React.createElement(Foo), 'span', ''
- ).toThrow(
+ ).toThrowError(
'Foo.state: must be set to an object or null'
)
+ undefined
it 'should render with null in the initial state property', ->
class Foo extends React.Component
@@ -166,6 +173,7 @@ describe 'ReactCoffeeScriptClass', ->
span()
test React.createElement(Foo), 'SPAN', ''
+ undefined
it 'setState through an event handler', ->
class Foo extends React.Component
@@ -183,6 +191,7 @@ describe 'ReactCoffeeScriptClass', ->
test React.createElement(Foo, initialValue: 'foo'), 'DIV', 'foo'
attachedListener()
expect(renderedName).toBe 'bar'
+ undefined
it 'should not implicitly bind event handlers', ->
class Foo extends React.Component
@@ -199,6 +208,7 @@ describe 'ReactCoffeeScriptClass', ->
test React.createElement(Foo, initialValue: 'foo'), 'DIV', 'foo'
expect(attachedListener).toThrow()
+ undefined
it 'renders using forceUpdate even when there is no state', ->
class Foo extends React.Component
@@ -217,6 +227,7 @@ describe 'ReactCoffeeScriptClass', ->
test React.createElement(Foo, initialValue: 'foo'), 'DIV', 'foo'
attachedListener()
expect(renderedName).toBe 'bar'
+ undefined
it 'will call all the normal life cycle methods', ->
lifeCycles = []
@@ -266,6 +277,7 @@ describe 'ReactCoffeeScriptClass', ->
lifeCycles = [] # reset
ReactDOM.unmountComponentAtNode container
expect(lifeCycles).toEqual ['will-unmount']
+ undefined
it 'warns when classic properties are defined on the instance,
but does not invoke them.', ->
@@ -292,19 +304,20 @@ describe 'ReactCoffeeScriptClass', ->
test React.createElement(Foo), 'SPAN', 'foo'
expect(getInitialStateWasCalled).toBe false
expect(getDefaultPropsWasCalled).toBe false
- expect(console.error.calls.length).toBe 4
- expect(console.error.argsForCall[0][0]).toContain(
+ expect(console.error.calls.count()).toBe 4
+ expect(console.error.calls.argsFor(0)[0]).toContain(
'getInitialState was defined on Foo, a plain JavaScript class.'
)
- expect(console.error.argsForCall[1][0]).toContain(
+ expect(console.error.calls.argsFor(1)[0]).toContain(
'getDefaultProps was defined on Foo, a plain JavaScript class.'
)
- expect(console.error.argsForCall[2][0]).toContain(
+ expect(console.error.calls.argsFor(2)[0]).toContain(
'propTypes was defined as an instance property on Foo.'
)
- expect(console.error.argsForCall[3][0]).toContain(
+ expect(console.error.calls.argsFor(3)[0]).toContain(
'contextTypes was defined as an instance property on Foo.'
)
+ undefined
it 'should warn when misspelling shouldComponentUpdate', ->
spyOn console, 'error'
@@ -317,12 +330,13 @@ describe 'ReactCoffeeScriptClass', ->
className: 'foo'
test React.createElement(NamedComponent), 'SPAN', 'foo'
- expect(console.error.calls.length).toBe 1
- expect(console.error.argsForCall[0][0]).toBe(
+ expect(console.error.calls.count()).toBe 1
+ expect(console.error.calls.argsFor(0)[0]).toBe(
'Warning: NamedComponent has a method called componentShouldUpdate().
Did you mean shouldComponentUpdate()? The name is phrased as a
question because the function is expected to return a value.'
)
+ undefined
it 'should warn when misspelling componentWillReceiveProps', ->
spyOn console, 'error'
@@ -335,11 +349,12 @@ describe 'ReactCoffeeScriptClass', ->
className: 'foo'
test React.createElement(NamedComponent), 'SPAN', 'foo'
- expect(console.error.calls.length).toBe 1
- expect(console.error.argsForCall[0][0]).toBe(
+ expect(console.error.calls.count()).toBe 1
+ expect(console.error.calls.argsFor(0)[0]).toBe(
'Warning: NamedComponent has a method called componentWillRecieveProps().
Did you mean componentWillReceiveProps()?'
)
+ undefined
it 'should throw AND warn when trying to access classic APIs', ->
spyOn console, 'error'
@@ -349,13 +364,14 @@ describe 'ReactCoffeeScriptClass', ->
expect(-> instance.isMounted()).toThrow()
expect(-> instance.setProps name: 'bar').toThrow()
expect(-> instance.replaceProps name: 'bar').toThrow()
- expect(console.error.calls.length).toBe 2
- expect(console.error.argsForCall[0][0]).toContain(
+ expect(console.error.calls.count()).toBe 2
+ expect(console.error.calls.argsFor(0)[0]).toContain(
'replaceState(...) is deprecated in plain JavaScript React classes'
)
- expect(console.error.argsForCall[1][0]).toContain(
+ expect(console.error.calls.argsFor(1)[0]).toContain(
'isMounted(...) is deprecated in plain JavaScript React classes'
)
+ undefined
it 'supports this.context passed via getChildContext', ->
class Bar extends React.Component
@@ -373,6 +389,7 @@ describe 'ReactCoffeeScriptClass', ->
React.createElement Bar
test React.createElement(Foo), 'DIV', 'bar-through-context'
+ undefined
it 'supports classic refs', ->
class Foo extends React.Component
@@ -383,8 +400,10 @@ describe 'ReactCoffeeScriptClass', ->
instance = test(React.createElement(Foo), 'DIV', 'foo')
expect(instance.refs.inner.getName()).toBe 'foo'
+ undefined
it 'supports drilling through to the DOM using findDOMNode', ->
instance = test Inner(name: 'foo'), 'DIV', 'foo'
node = ReactDOM.findDOMNode(instance)
expect(node).toBe container.firstChild
+ undefined
diff --git a/src/isomorphic/modern/class/__tests__/ReactES6Class-test.js b/src/isomorphic/modern/class/__tests__/ReactES6Class-test.js
index 17a2414c53..de2a5e591c 100644
--- a/src/isomorphic/modern/class/__tests__/ReactES6Class-test.js
+++ b/src/isomorphic/modern/class/__tests__/ReactES6Class-test.js
@@ -61,8 +61,8 @@ describe('ReactES6Class', function() {
class Foo extends React.Component { }
expect(() => ReactDOM.render(
, container)).toThrow();
- expect(console.error.calls.length).toBe(1);
- expect(console.error.argsForCall[0][0]).toBe(
+ expect(console.error.calls.count()).toBe(1);
+ expect(console.error.calls.argsFor(0)[0]).toBe(
'Warning: Foo(...): No `render` method found on the returned component ' +
'instance: you may have forgotten to define `render`.'
);
@@ -173,7 +173,7 @@ describe('ReactES6Class', function() {
return
;
}
}
- expect(() => test(
, 'span', '')).toThrow(
+ expect(() => test(
, 'span', '')).toThrowError(
'Foo.state: must be set to an object or null'
);
});
@@ -339,17 +339,17 @@ describe('ReactES6Class', function() {
test(
, 'SPAN', 'foo');
expect(getInitialStateWasCalled).toBe(false);
expect(getDefaultPropsWasCalled).toBe(false);
- expect(console.error.calls.length).toBe(4);
- expect(console.error.argsForCall[0][0]).toContain(
+ expect(console.error.calls.count()).toBe(4);
+ expect(console.error.calls.argsFor(0)[0]).toContain(
'getInitialState was defined on Foo, a plain JavaScript class.'
);
- expect(console.error.argsForCall[1][0]).toContain(
+ expect(console.error.calls.argsFor(1)[0]).toContain(
'getDefaultProps was defined on Foo, a plain JavaScript class.'
);
- expect(console.error.argsForCall[2][0]).toContain(
+ expect(console.error.calls.argsFor(2)[0]).toContain(
'propTypes was defined as an instance property on Foo.'
);
- expect(console.error.argsForCall[3][0]).toContain(
+ expect(console.error.calls.argsFor(3)[0]).toContain(
'contextTypes was defined as an instance property on Foo.'
);
});
@@ -367,8 +367,8 @@ describe('ReactES6Class', function() {
}
test(
, 'SPAN', 'foo');
- expect(console.error.calls.length).toBe(1);
- expect(console.error.argsForCall[0][0]).toBe(
+ expect(console.error.calls.count()).toBe(1);
+ expect(console.error.calls.argsFor(0)[0]).toBe(
'Warning: ' +
'NamedComponent has a method called componentShouldUpdate(). Did you ' +
'mean shouldComponentUpdate()? The name is phrased as a question ' +
@@ -389,8 +389,8 @@ describe('ReactES6Class', function() {
}
test(
, 'SPAN', 'foo');
- expect(console.error.calls.length).toBe(1);
- expect(console.error.argsForCall[0][0]).toBe(
+ expect(console.error.calls.count()).toBe(1);
+ expect(console.error.calls.argsFor(0)[0]).toBe(
'Warning: ' +
'NamedComponent has a method called componentWillRecieveProps(). Did ' +
'you mean componentWillReceiveProps()?'
@@ -404,11 +404,11 @@ describe('ReactES6Class', function() {
expect(() => instance.isMounted()).toThrow();
expect(() => instance.setProps({name: 'bar'})).toThrow();
expect(() => instance.replaceProps({name: 'bar'})).toThrow();
- expect(console.error.calls.length).toBe(2);
- expect(console.error.argsForCall[0][0]).toContain(
+ expect(console.error.calls.count()).toBe(2);
+ expect(console.error.calls.argsFor(0)[0]).toContain(
'replaceState(...) is deprecated in plain JavaScript React classes'
);
- expect(console.error.argsForCall[1][0]).toContain(
+ expect(console.error.calls.argsFor(1)[0]).toContain(
'isMounted(...) is deprecated in plain JavaScript React classes'
);
});
diff --git a/src/isomorphic/modern/class/__tests__/ReactTypeScriptClass-test.ts b/src/isomorphic/modern/class/__tests__/ReactTypeScriptClass-test.ts
index 0078265bcb..fe6d4910de 100644
--- a/src/isomorphic/modern/class/__tests__/ReactTypeScriptClass-test.ts
+++ b/src/isomorphic/modern/class/__tests__/ReactTypeScriptClass-test.ts
@@ -1,3 +1,6 @@
+///
+///
+
/*!
* Copyright 2015-present, Facebook, Inc.
* All rights reserved.
@@ -316,8 +319,8 @@ describe('ReactTypeScriptClass', function() {
expect(() => ReactDOM.render(React.createElement(Empty), container)).toThrow();
- expect((
console.error).argsForCall.length).toBe(1);
- expect((console.error).argsForCall[0][0]).toBe(
+ expect((console.error).calls.count()).toBe(1);
+ expect((console.error).calls.argsFor(0)[0]).toBe(
'Warning: Empty(...): No `render` method found on the returned ' +
'component instance: you may have forgotten to define `render`.'
);
@@ -358,15 +361,15 @@ describe('ReactTypeScriptClass', function() {
it('should throw with non-object in the initial state property', function() {
expect(() => test(React.createElement(ArrayState), 'span', ''))
- .toThrow(
+ .toThrowError(
'ArrayState.state: must be set to an object or null'
);
expect(() => test(React.createElement(StringState), 'span', ''))
- .toThrow(
+ .toThrowError(
'StringState.state: must be set to an object or null'
);
expect(() => test(React.createElement(NumberState), 'span', ''))
- .toThrow(
+ .toThrowError(
'NumberState.state: must be set to an object or null'
);
});
@@ -434,19 +437,19 @@ describe('ReactTypeScriptClass', function() {
test(React.createElement(ClassicProperties), 'SPAN', 'foo');
expect(getInitialStateWasCalled).toBe(false);
expect(getDefaultPropsWasCalled).toBe(false);
- expect((console.error).argsForCall.length).toBe(4);
- expect((console.error).argsForCall[0][0]).toContain(
+ expect((console.error).calls.count()).toBe(4);
+ expect((console.error).calls.argsFor(0)[0]).toContain(
'getInitialState was defined on ClassicProperties, ' +
'a plain JavaScript class.'
);
- expect((console.error).argsForCall[1][0]).toContain(
+ expect((console.error).calls.argsFor(1)[0]).toContain(
'getDefaultProps was defined on ClassicProperties, ' +
'a plain JavaScript class.'
);
- expect((console.error).argsForCall[2][0]).toContain(
+ expect((console.error).calls.argsFor(2)[0]).toContain(
'propTypes was defined as an instance property on ClassicProperties.'
);
- expect((console.error).argsForCall[3][0]).toContain(
+ expect((console.error).calls.argsFor(3)[0]).toContain(
'contextTypes was defined as an instance property on ClassicProperties.'
);
});
@@ -456,8 +459,8 @@ describe('ReactTypeScriptClass', function() {
test(React.createElement(MisspelledComponent1), 'SPAN', 'foo');
- expect((console.error).argsForCall.length).toBe(1);
- expect((console.error).argsForCall[0][0]).toBe(
+ expect((console.error).calls.count()).toBe(1);
+ expect((console.error).calls.argsFor(0)[0]).toBe(
'Warning: ' +
'MisspelledComponent1 has a method called componentShouldUpdate(). Did ' +
'you mean shouldComponentUpdate()? The name is phrased as a question ' +
@@ -470,8 +473,8 @@ describe('ReactTypeScriptClass', function() {
test(React.createElement(MisspelledComponent2), 'SPAN', 'foo');
- expect((console.error).argsForCall.length).toBe(1);
- expect((console.error).argsForCall[0][0]).toBe(
+ expect((console.error).calls.count()).toBe(1);
+ expect((console.error).calls.argsFor(0)[0]).toBe(
'Warning: ' +
'MisspelledComponent2 has a method called componentWillRecieveProps(). ' +
'Did you mean componentWillReceiveProps()?'
@@ -488,11 +491,11 @@ describe('ReactTypeScriptClass', function() {
expect(() => instance.isMounted()).toThrow();
expect(() => instance.setProps({ name: 'bar' })).toThrow();
expect(() => instance.replaceProps({ name: 'bar' })).toThrow();
- expect((console.error).argsForCall.length).toBe(2);
- expect((console.error).argsForCall[0][0]).toContain(
+ expect((console.error).calls.count()).toBe(2);
+ expect((console.error).calls.argsFor(0)[0]).toContain(
'replaceState(...) is deprecated in plain JavaScript React classes'
);
- expect((console.error).argsForCall[1][0]).toContain(
+ expect((console.error).calls.argsFor(1)[0]).toContain(
'isMounted(...) is deprecated in plain JavaScript React classes'
);
});
diff --git a/src/isomorphic/modern/class/__tests__/setupSpecEquivalenceReporter.js b/src/isomorphic/modern/class/__tests__/setupSpecEquivalenceReporter.js
new file mode 100644
index 0000000000..90e430f4c7
--- /dev/null
+++ b/src/isomorphic/modern/class/__tests__/setupSpecEquivalenceReporter.js
@@ -0,0 +1,31 @@
+/*!
+ * Copyright 2015-present, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ */
+
+'use strict';
+
+var expect = global.expect;
+
+var numExpectations = 0;
+
+global.expect = function() {
+ numExpectations += 1;
+ return expect.apply(this, arguments);
+};
+
+beforeEach(() => numExpectations = 0);
+
+jasmine.currentEnv_.addReporter({
+ specDone: (spec) => {
+ console.log(
+ `EQUIVALENCE: ${spec.description}, ` +
+ `status: ${spec.status}, ` +
+ `numExpectations: ${numExpectations}`
+ );
+ },
+});
diff --git a/src/isomorphic/modern/element/__tests__/ReactJSXElement-test.js b/src/isomorphic/modern/element/__tests__/ReactJSXElement-test.js
index 95126ca111..2e70b0253e 100644
--- a/src/isomorphic/modern/element/__tests__/ReactJSXElement-test.js
+++ b/src/isomorphic/modern/element/__tests__/ReactJSXElement-test.js
@@ -100,21 +100,33 @@ describe('ReactJSXElement', function() {
var a = 1;
var element = {a};
expect(element.props.children).toBe(a);
- expect(console.error.argsForCall.length).toBe(0);
+ expect(console.error.calls.count()).toBe(0);
});
it('does not override children if no JSX children are provided', function() {
spyOn(console, 'error');
var element = ;
expect(element.props.children).toBe('text');
- expect(console.error.argsForCall.length).toBe(0);
+ expect(console.error.calls.count()).toBe(0);
});
it('overrides children if null is provided as a JSX child', function() {
spyOn(console, 'error');
var element = {null};
expect(element.props.children).toBe(null);
- expect(console.error.argsForCall.length).toBe(0);
+ expect(console.error.calls.count()).toBe(0);
+ });
+
+ it('overrides children if undefined is provided as an argument', function() {
+ var element = {undefined};
+ expect(element.props.children).toBe(undefined);
+
+ var element2 = React.cloneElement(
+ ,
+ {},
+ undefined
+ );
+ expect(element2.props.children).toBe(undefined);
});
it('merges JSX children onto the children prop in an array', function() {
@@ -124,7 +136,7 @@ describe('ReactJSXElement', function() {
var c = 3;
var element = {a}{b}{c};
expect(element.props.children).toEqual([1, 2, 3]);
- expect(console.error.argsForCall.length).toBe(0);
+ expect(console.error.calls.count()).toBe(0);
});
it('allows static methods to be called using the type property', function() {
@@ -141,7 +153,7 @@ describe('ReactJSXElement', function() {
var element = ;
expect(element.type.someStaticMethod()).toBe('someReturnValue');
- expect(console.error.argsForCall.length).toBe(0);
+ expect(console.error.calls.count()).toBe(0);
});
it('identifies valid elements', function() {
diff --git a/src/isomorphic/modern/element/__tests__/ReactJSXElementValidator-test.js b/src/isomorphic/modern/element/__tests__/ReactJSXElementValidator-test.js
index 1e2890e9f0..827ab73ee5 100644
--- a/src/isomorphic/modern/element/__tests__/ReactJSXElementValidator-test.js
+++ b/src/isomorphic/modern/element/__tests__/ReactJSXElementValidator-test.js
@@ -47,8 +47,8 @@ describe('ReactJSXElementValidator', function() {
void {[, ]};
- expect(console.error.argsForCall.length).toBe(1);
- expect(console.error.argsForCall[0][0]).toContain(
+ expect(console.error.calls.count()).toBe(1);
+ expect(console.error.calls.argsFor(0)[0]).toContain(
'Each child in an array or iterator should have a unique "key" prop.'
);
});
@@ -74,8 +74,8 @@ describe('ReactJSXElementValidator', function() {
ReactTestUtils.renderIntoDocument();
- expect(console.error.argsForCall.length).toBe(1);
- expect(console.error.argsForCall[0][0]).toContain(
+ expect(console.error.calls.count()).toBe(1);
+ expect(console.error.calls.argsFor(0)[0]).toContain(
'Each child in an array or iterator should have a unique "key" prop. ' +
'Check the render method of `InnerComponent`. ' +
'It was passed a child from ComponentWrapper. '
@@ -99,8 +99,8 @@ describe('ReactJSXElementValidator', function() {
void {iterable};
- expect(console.error.argsForCall.length).toBe(1);
- expect(console.error.argsForCall[0][0]).toContain(
+ expect(console.error.calls.count()).toBe(1);
+ expect(console.error.calls.argsFor(0)[0]).toContain(
'Each child in an array or iterator should have a unique "key" prop.'
);
});
@@ -110,7 +110,7 @@ describe('ReactJSXElementValidator', function() {
void {[, ]};
- expect(console.error.argsForCall.length).toBe(0);
+ expect(console.error.calls.count()).toBe(0);
});
it('does not warns for iterable elements with keys', function() {
@@ -133,7 +133,7 @@ describe('ReactJSXElementValidator', function() {
void {iterable};
- expect(console.error.argsForCall.length).toBe(0);
+ expect(console.error.calls.count()).toBe(0);
});
it('does not warn for numeric keys in entry iterable as a child', function() {
@@ -154,7 +154,7 @@ describe('ReactJSXElementValidator', function() {
void {iterable};
- expect(console.error.argsForCall.length).toBe(0);
+ expect(console.error.calls.count()).toBe(0);
});
it('does not warn when the element is directly as children', function() {
@@ -162,7 +162,7 @@ describe('ReactJSXElementValidator', function() {
void ;
- expect(console.error.argsForCall.length).toBe(0);
+ expect(console.error.calls.count()).toBe(0);
});
it('does not warn when the child array contains non-elements', function() {
@@ -170,7 +170,7 @@ describe('ReactJSXElementValidator', function() {
void {[{}, {}]};
- expect(console.error.argsForCall.length).toBe(0);
+ expect(console.error.calls.count()).toBe(0);
});
// TODO: These warnings currently come from the composite component, but
@@ -195,10 +195,14 @@ describe('ReactJSXElementValidator', function() {
}
}
ReactTestUtils.renderIntoDocument();
- expect(console.error.argsForCall[0][0]).toBe(
- 'Warning: Failed propType: ' +
+ expect(
+ console.error.calls.argsFor(0)[0].replace(/\(at .+?:\d+\)/g, '(at **)')
+ ).toBe(
+ 'Warning: Failed prop type: ' +
'Invalid prop `color` of type `number` supplied to `MyComp`, ' +
- 'expected `string`. Check the render method of `ParentComp`.'
+ 'expected `string`.\n' +
+ ' in MyComp (at **)\n' +
+ ' in ParentComp (at **)'
);
});
@@ -213,25 +217,25 @@ describe('ReactJSXElementValidator', function() {
void ;
void ;
void ;
- expect(console.error.calls.length).toBe(4);
- expect(console.error.argsForCall[0][0]).toContain(
+ expect(console.error.calls.count()).toBe(4);
+ expect(console.error.calls.argsFor(0)[0]).toContain(
'type should not be null, undefined, boolean, or number. It should be ' +
'a string (for DOM elements) or a ReactClass (for composite components).'
);
- expect(console.error.argsForCall[1][0]).toContain(
+ expect(console.error.calls.argsFor(1)[0]).toContain(
'type should not be null, undefined, boolean, or number. It should be ' +
'a string (for DOM elements) or a ReactClass (for composite components).'
);
- expect(console.error.argsForCall[2][0]).toContain(
+ expect(console.error.calls.argsFor(2)[0]).toContain(
'type should not be null, undefined, boolean, or number. It should be ' +
'a string (for DOM elements) or a ReactClass (for composite components).'
);
- expect(console.error.argsForCall[3][0]).toContain(
+ expect(console.error.calls.argsFor(3)[0]).toContain(
'type should not be null, undefined, boolean, or number. It should be ' +
'a string (for DOM elements) or a ReactClass (for composite components).'
);
void ;
- expect(console.error.calls.length).toBe(4);
+ expect(console.error.calls.count()).toBe(4);
});
it('should check default prop values', function() {
@@ -241,10 +245,13 @@ describe('ReactJSXElementValidator', function() {
ReactTestUtils.renderIntoDocument();
- expect(console.error.calls.length).toBe(1);
- expect(console.error.argsForCall[0][0]).toBe(
- 'Warning: Failed propType: ' +
- 'Required prop `prop` was not specified in `RequiredPropComponent`.'
+ expect(console.error.calls.count()).toBe(1);
+ expect(
+ console.error.calls.argsFor(0)[0].replace(/\(at .+?:\d+\)/g, '(at **)')
+ ).toBe(
+ 'Warning: Failed prop type: ' +
+ 'Required prop `prop` was not specified in `RequiredPropComponent`.\n' +
+ ' in RequiredPropComponent (at **)'
);
});
@@ -253,10 +260,13 @@ describe('ReactJSXElementValidator', function() {
ReactTestUtils.renderIntoDocument();
- expect(console.error.calls.length).toBe(1);
- expect(console.error.argsForCall[0][0]).toBe(
- 'Warning: Failed propType: ' +
- 'Required prop `prop` was not specified in `RequiredPropComponent`.'
+ expect(console.error.calls.count()).toBe(1);
+ expect(
+ console.error.calls.argsFor(0)[0].replace(/\(at .+?:\d+\)/g, '(at **)')
+ ).toBe(
+ 'Warning: Failed prop type: ' +
+ 'Required prop `prop` was not specified in `RequiredPropComponent`.\n' +
+ ' in RequiredPropComponent (at **)'
);
});
@@ -266,22 +276,28 @@ describe('ReactJSXElementValidator', function() {
ReactTestUtils.renderIntoDocument();
ReactTestUtils.renderIntoDocument();
- expect(console.error.calls.length).toBe(2);
- expect(console.error.argsForCall[0][0]).toBe(
- 'Warning: Failed propType: ' +
- 'Required prop `prop` was not specified in `RequiredPropComponent`.'
+ expect(console.error.calls.count()).toBe(2);
+ expect(
+ console.error.calls.argsFor(0)[0].replace(/\(at .+?:\d+\)/g, '(at **)')
+ ).toBe(
+ 'Warning: Failed prop type: ' +
+ 'Required prop `prop` was not specified in `RequiredPropComponent`.\n' +
+ ' in RequiredPropComponent (at **)'
);
- expect(console.error.argsForCall[1][0]).toBe(
- 'Warning: Failed propType: ' +
+ expect(
+ console.error.calls.argsFor(1)[0].replace(/\(at .+?:\d+\)/g, '(at **)')
+ ).toBe(
+ 'Warning: Failed prop type: ' +
'Invalid prop `prop` of type `number` supplied to ' +
- '`RequiredPropComponent`, expected `string`.'
+ '`RequiredPropComponent`, expected `string`.\n' +
+ ' in RequiredPropComponent (at **)'
);
ReactTestUtils.renderIntoDocument();
// Should not error for strings
- expect(console.error.calls.length).toBe(2);
+ expect(console.error.calls.count()).toBe(2);
});
it('should warn on invalid prop types', function() {
@@ -299,8 +315,8 @@ describe('ReactJSXElementValidator', function() {
prop: null,
};
ReactTestUtils.renderIntoDocument();
- expect(console.error.calls.length).toBe(1);
- expect(console.error.argsForCall[0][0]).toContain(
+ expect(console.error.calls.count()).toBe(1);
+ expect(console.error.calls.argsFor(0)[0]).toContain(
'NullPropTypeComponent: prop type `prop` is invalid; it must be a ' +
'function, usually from React.PropTypes.'
);
@@ -317,8 +333,8 @@ describe('ReactJSXElementValidator', function() {
prop: null,
};
ReactTestUtils.renderIntoDocument();
- expect(console.error.calls.length).toBe(1);
- expect(console.error.argsForCall[0][0]).toContain(
+ expect(console.error.calls.count()).toBe(1);
+ expect(console.error.calls.argsFor(0)[0]).toContain(
'NullContextTypeComponent: context type `prop` is invalid; it must ' +
'be a function, usually from React.PropTypes.'
);
@@ -335,8 +351,8 @@ describe('ReactJSXElementValidator', function() {
prop: 'foo',
});
ReactTestUtils.renderIntoDocument();
- expect(console.error.calls.length).toBe(1);
- expect(console.error.argsForCall[0][0]).toContain(
+ expect(console.error.calls.count()).toBe(1);
+ expect(console.error.calls.argsFor(0)[0]).toContain(
'getDefaultProps is only used on classic React.createClass definitions.' +
' Use a static property named `defaultProps` instead.'
);
diff --git a/src/renderers/art/ReactART.js b/src/renderers/art/ReactART.js
new file mode 100644
index 0000000000..be85e1f238
--- /dev/null
+++ b/src/renderers/art/ReactART.js
@@ -0,0 +1,641 @@
+/**
+ * Copyright (c) 2013-present Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @providesModule ReactART
+ */
+
+'use strict';
+
+require('art/modes/current').setCurrent(
+ require('art/modes/fast-noSideEffects') // Flip this to DOM mode for debugging
+);
+
+const Transform = require('art/core/transform');
+const Mode = require('art/modes/current');
+
+const React = require('React');
+const ReactDOM = require('ReactDOM');
+const ReactInstanceMap = require('ReactInstanceMap');
+const ReactMultiChild = require('ReactMultiChild');
+const ReactUpdates = require('ReactUpdates');
+
+const emptyObject = require('emptyObject');
+const invariant = require('invariant');
+
+const assign = require('object-assign');
+const pooledTransform = new Transform();
+
+// Utilities
+
+function childrenAsString(children) {
+ if (!children) {
+ return '';
+ }
+ if (typeof children === 'string') {
+ return children;
+ }
+ if (children.length) {
+ return children.join('\n');
+ }
+ return '';
+}
+
+function createComponent(name) {
+ const ReactARTComponent = function(element) {
+ this.node = null;
+ this.subscriptions = null;
+ this.listeners = null;
+ this._mountImage = null;
+ this._renderedChildren = null;
+ this.construct(element);
+ };
+ ReactARTComponent.displayName = name;
+ for (let i = 1, l = arguments.length; i < l; i++) {
+ assign(ReactARTComponent.prototype, arguments[i]);
+ }
+
+ return ReactARTComponent;
+}
+
+/**
+ * Insert `node` into `parentNode` after `referenceNode`.
+ */
+function injectAfter(parentNode, referenceNode, node) {
+ let beforeNode;
+ if (node.parentNode === parentNode &&
+ node.previousSibling === referenceNode) {
+ return;
+ }
+ if (referenceNode == null) {
+ // node is supposed to be first.
+ beforeNode = parentNode.firstChild;
+ } else {
+ // node is supposed to be after referenceNode.
+ beforeNode = referenceNode.nextSibling;
+ }
+ if (beforeNode && beforeNode.previousSibling !== node) {
+ // Cases where `node === beforeNode` should get filtered out by earlier
+ // checks and the behavior isn't well-defined.
+ invariant(
+ node !== beforeNode,
+ 'ReactART: Can not insert node before itself'
+ );
+ node.injectBefore(beforeNode);
+ } else if (node.parentNode !== parentNode) {
+ node.inject(parentNode);
+ }
+}
+
+// ContainerMixin for components that can hold ART nodes
+
+const ContainerMixin = assign({}, ReactMultiChild.Mixin, {
+
+ /**
+ * Moves a child component to the supplied index.
+ *
+ * @param {ReactComponent} child Component to move.
+ * @param {number} toIndex Destination index of the element.
+ * @protected
+ */
+ moveChild: function(child, afterNode, toIndex, lastIndex) {
+ const childNode = child._mountImage;
+ injectAfter(this.node, afterNode, childNode);
+ },
+
+ /**
+ * Creates a child component.
+ *
+ * @param {ReactComponent} child Component to create.
+ * @param {object} childNode ART node to insert.
+ * @protected
+ */
+ createChild: function(child, afterNode, childNode) {
+ child._mountImage = childNode;
+ injectAfter(this.node, afterNode, childNode);
+ },
+
+ /**
+ * Removes a child component.
+ *
+ * @param {ReactComponent} child Child to remove.
+ * @protected
+ */
+ removeChild: function(child) {
+ child._mountImage.eject();
+ child._mountImage = null;
+ },
+
+ updateChildrenAtRoot: function(nextChildren, transaction) {
+ this.updateChildren(nextChildren, transaction, emptyObject);
+ },
+
+ mountAndInjectChildrenAtRoot: function(children, transaction) {
+ this.mountAndInjectChildren(children, transaction, emptyObject);
+ },
+
+ /**
+ * Override to bypass batch updating because it is not necessary.
+ *
+ * @param {?object} nextChildren.
+ * @param {ReactReconcileTransaction} transaction
+ * @internal
+ * @override {ReactMultiChild.Mixin.updateChildren}
+ */
+ updateChildren: function(nextChildren, transaction, context) {
+ this._updateChildren(nextChildren, transaction, context);
+ },
+
+ // Shorthands
+
+ mountAndInjectChildren: function(children, transaction, context) {
+ const mountedImages = this.mountChildren(
+ children,
+ transaction,
+ context
+ );
+ // Each mount image corresponds to one of the flattened children
+ let i = 0;
+ for (let key in this._renderedChildren) {
+ if (this._renderedChildren.hasOwnProperty(key)) {
+ const child = this._renderedChildren[key];
+ child._mountImage = mountedImages[i];
+ mountedImages[i].inject(this.node);
+ i++;
+ }
+ }
+ }
+
+});
+
+// Surface is a React DOM Component, not an ART component. It serves as the
+// entry point into the ART reconciler.
+
+const Surface = React.createClass({
+
+ displayName: 'Surface',
+
+ mixins: [ContainerMixin],
+
+ componentDidMount: function() {
+ const domNode = ReactDOM.findDOMNode(this);
+
+ this.node = Mode.Surface(+this.props.width, +this.props.height, domNode);
+
+ const transaction = ReactUpdates.ReactReconcileTransaction.getPooled();
+ transaction.perform(
+ this.mountAndInjectChildren,
+ this,
+ this.props.children,
+ transaction,
+ ReactInstanceMap.get(this)._context
+ );
+ ReactUpdates.ReactReconcileTransaction.release(transaction);
+ },
+
+ componentDidUpdate: function(oldProps) {
+ const node = this.node;
+ if (this.props.width != oldProps.width ||
+ this.props.height != oldProps.height) {
+ node.resize(+this.props.width, +this.props.height);
+ }
+
+ const transaction = ReactUpdates.ReactReconcileTransaction.getPooled();
+ transaction.perform(
+ this.updateChildren,
+ this,
+ this.props.children,
+ transaction,
+ ReactInstanceMap.get(this)._context
+ );
+ ReactUpdates.ReactReconcileTransaction.release(transaction);
+
+ if (node.render) {
+ node.render();
+ }
+ },
+
+ componentWillUnmount: function() {
+ this.unmountChildren();
+ },
+
+ render: function() {
+ // This is going to be a placeholder because we don't know what it will
+ // actually resolve to because ART may render canvas, vml or svg tags here.
+ // We only allow a subset of properties since others might conflict with
+ // ART's properties.
+ const props = this.props;
+
+ // TODO: ART's Canvas Mode overrides surface title and cursor
+ const Tag = Mode.Surface.tagName;
+ return (
+
+ );
+ }
+
+});
+
+// Various nodes that can go into a surface
+
+const EventTypes = {
+ onMouseMove: 'mousemove',
+ onMouseOver: 'mouseover',
+ onMouseOut: 'mouseout',
+ onMouseUp: 'mouseup',
+ onMouseDown: 'mousedown',
+ onClick: 'click'
+};
+
+const NodeMixin = {
+
+ construct: function(element) {
+ this._currentElement = element;
+ },
+
+ getNativeNode: function() {
+ return this.node;
+ },
+
+ getPublicInstance: function() {
+ return this.node;
+ },
+
+ putEventListener: function(type, listener) {
+ const subscriptions = this.subscriptions || (this.subscriptions = {});
+ const listeners = this.listeners || (this.listeners = {});
+ listeners[type] = listener;
+ if (listener) {
+ if (!subscriptions[type]) {
+ subscriptions[type] = this.node.subscribe(type, listener, this);
+ }
+ } else {
+ if (subscriptions[type]) {
+ subscriptions[type]();
+ delete subscriptions[type];
+ }
+ }
+ },
+
+ handleEvent: function(event) {
+ const listener = this.listeners[event.type];
+ if (!listener) {
+ return;
+ }
+ if (typeof listener === 'function') {
+ listener.call(this, event);
+ } else if (listener.handleEvent) {
+ listener.handleEvent(event);
+ }
+ },
+
+ destroyEventListeners: function() {
+ const subscriptions = this.subscriptions;
+ if (subscriptions) {
+ for (let type in subscriptions) {
+ subscriptions[type]();
+ }
+ }
+ this.subscriptions = null;
+ this.listeners = null;
+ },
+
+ applyNodeProps: function(oldProps, props) {
+ const node = this.node;
+
+ const scaleX = props.scaleX != null ? props.scaleX :
+ props.scale != null ? props.scale : 1;
+ const scaleY = props.scaleY != null ? props.scaleY :
+ props.scale != null ? props.scale : 1;
+
+ pooledTransform
+ .transformTo(1, 0, 0, 1, 0, 0)
+ .move(props.x || 0, props.y || 0)
+ .rotate(props.rotation || 0, props.originX, props.originY)
+ .scale(scaleX, scaleY, props.originX, props.originY);
+
+ if (props.transform != null) {
+ pooledTransform.transform(props.transform);
+ }
+
+ if (node.xx !== pooledTransform.xx || node.yx !== pooledTransform.yx ||
+ node.xy !== pooledTransform.xy || node.yy !== pooledTransform.yy ||
+ node.x !== pooledTransform.x || node.y !== pooledTransform.y) {
+ node.transformTo(pooledTransform);
+ }
+
+ if (props.cursor !== oldProps.cursor || props.title !== oldProps.title) {
+ node.indicate(props.cursor, props.title);
+ }
+
+ if (node.blend && props.opacity !== oldProps.opacity) {
+ node.blend(props.opacity == null ? 1 : props.opacity);
+ }
+
+ if (props.visible !== oldProps.visible) {
+ if (props.visible == null || props.visible) {
+ node.show();
+ } else {
+ node.hide();
+ }
+ }
+
+ for (let type in EventTypes) {
+ this.putEventListener(EventTypes[type], props[type]);
+ }
+ },
+
+ mountComponentIntoNode: function(rootID, container) {
+ throw new Error(
+ 'You cannot render an ART component standalone. ' +
+ 'You need to wrap it in a Surface.'
+ );
+ }
+
+};
+
+// Group
+
+const Group = createComponent('Group', NodeMixin, ContainerMixin, {
+
+ mountComponent: function(
+ transaction,
+ nativeParent,
+ nativeContainerInfo,
+ context
+ ) {
+ this.node = Mode.Group();
+ const props = this._currentElement.props;
+ this.applyGroupProps(emptyObject, props);
+ this.mountAndInjectChildren(props.children, transaction, context);
+ return this.node;
+ },
+
+ receiveComponent: function(nextComponent, transaction, context) {
+ const props = nextComponent.props;
+ const oldProps = this._currentElement.props;
+ this.applyGroupProps(oldProps, props);
+ this.updateChildren(props.children, transaction, context);
+ this._currentElement = nextComponent;
+ },
+
+ applyGroupProps: function(oldProps, props) {
+ this.node.width = props.width;
+ this.node.height = props.height;
+ this.applyNodeProps(oldProps, props);
+ },
+
+ unmountComponent: function() {
+ this.destroyEventListeners();
+ this.unmountChildren();
+ }
+
+});
+
+// ClippingRectangle
+const ClippingRectangle = createComponent(
+ 'ClippingRectangle', NodeMixin, ContainerMixin, {
+
+ mountComponent: function(
+ transaction,
+ nativeParent,
+ nativeContainerInfo,
+ context
+ ) {
+ this.node = Mode.ClippingRectangle();
+ const props = this._currentElement.props;
+ this.applyClippingProps(emptyObject, props);
+ this.mountAndInjectChildren(props.children, transaction, context);
+ return this.node;
+ },
+
+ receiveComponent: function(nextComponent, transaction, context) {
+ const props = nextComponent.props;
+ const oldProps = this._currentElement.props;
+ this.applyClippingProps(oldProps, props);
+ this.updateChildren(props.children, transaction, context);
+ this._currentElement = nextComponent;
+ },
+
+ applyClippingProps: function(oldProps, props) {
+ this.node.width = props.width;
+ this.node.height = props.height;
+ this.node.x = props.x;
+ this.node.y = props.y;
+ this.applyNodeProps(oldProps, props);
+ },
+
+ unmountComponent: function() {
+ this.destroyEventListeners();
+ this.unmountChildren();
+ }
+
+});
+
+
+// Renderables
+
+const RenderableMixin = assign({}, NodeMixin, {
+
+ applyRenderableProps: function(oldProps, props) {
+ if (oldProps.fill !== props.fill) {
+ if (props.fill && props.fill.applyFill) {
+ props.fill.applyFill(this.node);
+ } else {
+ this.node.fill(props.fill);
+ }
+ }
+ if (
+ oldProps.stroke !== props.stroke ||
+ oldProps.strokeWidth !== props.strokeWidth ||
+ oldProps.strokeCap !== props.strokeCap ||
+ oldProps.strokeJoin !== props.strokeJoin ||
+ // TODO: Consider a deep check of stokeDash.
+ // This may benefit the VML version in IE.
+ oldProps.strokeDash !== props.strokeDash
+ ) {
+ this.node.stroke(
+ props.stroke,
+ props.strokeWidth,
+ props.strokeCap,
+ props.strokeJoin,
+ props.strokeDash
+ );
+ }
+ this.applyNodeProps(oldProps, props);
+ },
+
+ unmountComponent: function() {
+ this.destroyEventListeners();
+ }
+
+});
+
+// Shape
+
+const Shape = createComponent('Shape', RenderableMixin, {
+
+ construct: function(element) {
+ this._currentElement = element;
+ this._oldDelta = null;
+ this._oldPath = null;
+ },
+
+ mountComponent: function(
+ transaction,
+ nativeParent,
+ nativeContainerInfo,
+ context
+ ) {
+ this.node = Mode.Shape();
+ const props = this._currentElement.props;
+ this.applyShapeProps(emptyObject, props);
+ return this.node;
+ },
+
+ receiveComponent: function(nextComponent, transaction, context) {
+ const props = nextComponent.props;
+ const oldProps = this._currentElement.props;
+ this.applyShapeProps(oldProps, props);
+ this._currentElement = nextComponent;
+ },
+
+ applyShapeProps: function(oldProps, props) {
+ const oldDelta = this._oldDelta;
+ const oldPath = this._oldPath;
+ const path = props.d || childrenAsString(props.children);
+
+ if (path.delta !== oldDelta ||
+ path !== oldPath ||
+ oldProps.width !== props.width ||
+ oldProps.height !== props.height) {
+
+ this.node.draw(
+ path,
+ props.width,
+ props.height
+ );
+
+ this._oldPath = path;
+ this._oldDelta = path.delta;
+ }
+
+ this.applyRenderableProps(oldProps, props);
+ }
+
+});
+
+// Text
+
+const Text = createComponent('Text', RenderableMixin, {
+
+ construct: function(element) {
+ this._currentElement = element;
+ this._oldString = null;
+ },
+
+ mountComponent: function(
+ transaction,
+ nativeParent,
+ nativeContainerInfo,
+ context
+ ) {
+ const props = this._currentElement.props;
+ const newString = childrenAsString(props.children);
+ this.node = Mode.Text(newString, props.font, props.alignment, props.path);
+ this._oldString = newString;
+ this.applyRenderableProps(emptyObject, props);
+ return this.node;
+ },
+
+ isSameFont: function(oldFont, newFont) {
+ if (oldFont === newFont) {
+ return true;
+ }
+ if (typeof newFont === 'string' || typeof oldFont === 'string') {
+ return false;
+ }
+ return (
+ newFont.fontSize === oldFont.fontSize &&
+ newFont.fontStyle === oldFont.fontStyle &&
+ newFont.fontVariant === oldFont.fontVariant &&
+ newFont.fontWeight === oldFont.fontWeight &&
+ newFont.fontFamily === oldFont.fontFamily
+ );
+ },
+
+ receiveComponent: function(nextComponent, transaction, context) {
+ const props = nextComponent.props;
+ const oldProps = this._currentElement.props;
+
+ const oldString = this._oldString;
+ const newString = childrenAsString(props.children);
+
+ if (oldString !== newString ||
+ !this.isSameFont(oldProps.font, props.font) ||
+ oldProps.alignment !== props.alignment ||
+ oldProps.path !== props.path) {
+ this.node.draw(
+ newString,
+ props.font,
+ props.alignment,
+ props.path
+ );
+ this._oldString = newString;
+ }
+
+ this.applyRenderableProps(oldProps, props);
+ this._currentElement = nextComponent;
+ }
+
+});
+
+// Declarative fill type objects - API design not finalized
+
+const slice = Array.prototype.slice;
+
+function LinearGradient(stops, x1, y1, x2, y2) {
+ this.args = slice.call(arguments);
+}
+
+LinearGradient.prototype.applyFill = function(node) {
+ node.fillLinear.apply(node, this.args);
+};
+
+function RadialGradient(stops, fx, fy, rx, ry, cx, cy) {
+ this.args = slice.call(arguments);
+}
+
+RadialGradient.prototype.applyFill = function(node) {
+ node.fillRadial.apply(node, this.args);
+};
+
+function Pattern(url, width, height, left, top) {
+ this.args = slice.call(arguments);
+}
+
+Pattern.prototype.applyFill = function(node) {
+ node.fillImage.apply(node, this.args);
+};
+
+module.exports = {
+ ClippingRectangle,
+ Group,
+ LinearGradient,
+ Path: Mode.Path,
+ Pattern,
+ RadialGradient,
+ Shape,
+ Surface,
+ Text,
+ Transform,
+};
diff --git a/src/renderers/art/__tests__/ReactART-test.js b/src/renderers/art/__tests__/ReactART-test.js
new file mode 100644
index 0000000000..546a3cf296
--- /dev/null
+++ b/src/renderers/art/__tests__/ReactART-test.js
@@ -0,0 +1,289 @@
+/**
+ * Copyright (c) 2013-present Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @emails react-core
+ */
+
+/*jslint evil: true */
+
+'use strict';
+
+jest
+ .unmock('ReactART');
+
+var React = require('React');
+var ReactDOM = require('ReactDOM');
+var ReactTestUtils = require('ReactTestUtils');
+
+var Group;
+var Shape;
+var Surface;
+var TestComponent;
+
+var Missing = {};
+
+var ReactART = require('ReactART');
+var ARTSVGMode = require('art/modes/svg');
+var ARTCurrentMode = require('art/modes/current');
+
+function testDOMNodeStructure(domNode, expectedStructure) {
+ expect(domNode).toBeDefined();
+ expect(domNode.nodeName).toBe(expectedStructure.nodeName);
+ for (var prop in expectedStructure) {
+ if (!expectedStructure.hasOwnProperty(prop)) continue;
+ if (prop != 'nodeName' && prop != 'children') {
+ if (expectedStructure[prop] === Missing) {
+ expect(domNode.hasAttribute(prop)).toBe(false);
+ } else {
+ expect(domNode.getAttribute(prop)).toBe(expectedStructure[prop]);
+ }
+ }
+ }
+ if (expectedStructure.children) {
+ expectedStructure.children.forEach(function(subTree, index) {
+ testDOMNodeStructure(domNode.childNodes[index], subTree);
+ });
+ }
+}
+
+describe('ReactART', function() {
+
+ beforeEach(function() {
+ ARTCurrentMode.setCurrent(ARTSVGMode);
+
+ Group = ReactART.Group;
+ Shape = ReactART.Shape;
+ Surface = ReactART.Surface;
+
+ TestComponent = React.createClass({
+ render: function() {
+
+ var a =
+ ;
+
+ var b =
+
+ M64.564,38.583H54l0.008-5.834c0-3.035,0.293-4.666,4.657-4.666
+ h5.833V16.429h-9.33c-11.213,0-15.159,5.654-15.159,15.16v6.994
+ h-6.99v11.652h6.99v33.815H54V50.235h9.331L64.564,38.583z
+ ;
+
+ var c = ;
+
+ return (
+
+
+ {this.props.flipped ? [b, a, c] : [a, b, c]}
+
+
+ );
+ }
+ });
+ });
+
+ it('should have the correct lifecycle state', function() {
+ var instance = ;
+ instance = ReactTestUtils.renderIntoDocument(instance);
+ var group = instance.refs.group;
+ // Duck type test for an ART group
+ expect(typeof group.indicate).toBe('function');
+ });
+
+ it('should render a reasonable SVG structure in SVG mode', function() {
+ var instance = ;
+ instance = ReactTestUtils.renderIntoDocument(instance);
+
+ var expectedStructure = {
+ nodeName: 'svg',
+ width: '150',
+ height: '200',
+ children: [
+ { nodeName: 'defs' },
+ {
+ nodeName: 'g',
+ children: [
+ {
+ nodeName: 'defs',
+ children: [
+ { nodeName: 'linearGradient' }
+ ]
+ },
+ { nodeName: 'path' },
+ { nodeName: 'path' },
+ { nodeName: 'g' }
+ ]
+ }
+ ]
+ };
+
+ var realNode = ReactDOM.findDOMNode(instance);
+ testDOMNodeStructure(realNode, expectedStructure);
+ });
+
+ it('should be able to reorder components', function() {
+ var container = document.createElement('div');
+ var instance = ReactDOM.render(, container);
+
+ var expectedStructure = {
+ nodeName: 'svg',
+ children: [
+ { nodeName: 'defs' },
+ {
+ nodeName: 'g',
+ children: [
+ { nodeName: 'defs' },
+ { nodeName: 'path', opacity: '0.1' },
+ { nodeName: 'path', opacity: Missing },
+ { nodeName: 'g' }
+ ]
+ }
+ ]
+ };
+
+ var realNode = ReactDOM.findDOMNode(instance);
+ testDOMNodeStructure(realNode, expectedStructure);
+
+ ReactDOM.render(, container);
+
+ var expectedNewStructure = {
+ nodeName: 'svg',
+ children: [
+ { nodeName: 'defs' },
+ {
+ nodeName: 'g',
+ children: [
+ { nodeName: 'defs' },
+ { nodeName: 'path', opacity: Missing },
+ { nodeName: 'path', opacity: '0.1' },
+ { nodeName: 'g' }
+ ]
+ }
+ ]
+ };
+
+ testDOMNodeStructure(realNode, expectedNewStructure);
+ });
+
+ it('should be able to reorder many components', function() {
+ var container = document.createElement('div');
+
+ var Component = React.createClass({
+ render: function() {
+ var chars = this.props.chars.split('');
+ return (
+
+ {chars.map((text) => )}
+
+ );
+ },
+ });
+
+ // Mini multi-child stress test: lots of reorders, some adds, some removes.
+ var before = 'abcdefghijklmnopqrst';
+ var after = 'mxhpgwfralkeoivcstzy';
+
+ var instance = ReactDOM.render(, container);
+ var realNode = ReactDOM.findDOMNode(instance);
+ expect(realNode.textContent).toBe(before);
+
+ instance = ReactDOM.render(, container);
+ expect(realNode.textContent).toBe(after);
+
+ ReactDOM.unmountComponentAtNode(container);
+ });
+
+ it('renders composite with lifecycle inside group', function() {
+ var mounted = false;
+ var CustomShape = React.createClass({
+ render: function() {
+ return ;
+ },
+ componentDidMount: function() {
+ mounted = true;
+ }
+ });
+ ReactTestUtils.renderIntoDocument(
+
+
+
+
+
+ );
+ expect(mounted).toBe(true);
+ });
+
+ it('resolves refs before componentDidMount', function() {
+ var CustomShape = React.createClass({
+ render: function() {
+ return ;
+ }
+ });
+ var ref = null;
+ var Outer = React.createClass({
+ componentDidMount: function() {
+ ref = this.refs.test;
+ },
+ render: function() {
+ return (
+
+
+
+
+
+ );
+ }
+ });
+ ReactTestUtils.renderIntoDocument();
+ expect(ref.constructor).toBe(CustomShape);
+ });
+
+ it('resolves refs before componentDidUpdate', function() {
+ var CustomShape = React.createClass({
+ render: function() {
+ return ;
+ }
+ });
+ var ref = {};
+ var Outer = React.createClass({
+ componentDidMount: function() {
+ ref = this.refs.test;
+ },
+ componentDidUpdate: function() {
+ ref = this.refs.test;
+ },
+ render: function() {
+ return (
+
+
+ {this.props.mountCustomShape && }
+
+
+ );
+ }
+ });
+ var container = document.createElement('div');
+ ReactDOM.render(, container);
+ expect(ref).not.toBeDefined();
+ ReactDOM.render(, container);
+ expect(ref.constructor).toBe(CustomShape);
+ });
+
+});
diff --git a/src/renderers/dom/ReactDOM.js b/src/renderers/dom/ReactDOM.js
index 7e7fbe4639..1619bfd4d4 100644
--- a/src/renderers/dom/ReactDOM.js
+++ b/src/renderers/dom/ReactDOM.js
@@ -21,7 +21,7 @@ var ReactUpdates = require('ReactUpdates');
var ReactVersion = require('ReactVersion');
var findDOMNode = require('findDOMNode');
-var getNativeComponentFromComposite = require('getNativeComponentFromComposite');
+var getHostComponentFromComposite = require('getHostComponentFromComposite');
var renderSubtreeIntoContainer = require('renderSubtreeIntoContainer');
var warning = require('warning');
@@ -51,7 +51,7 @@ if (
getNodeFromInstance: function(inst) {
// inst is an internal instance (but could be a composite)
if (inst._renderedComponent) {
- inst = getNativeComponentFromComposite(inst);
+ inst = getHostComponentFromComposite(inst);
}
if (inst) {
return ReactDOMComponentTree.getNodeFromInstance(inst);
diff --git a/src/renderers/dom/__tests__/ReactDOMProduction-test.js b/src/renderers/dom/__tests__/ReactDOMProduction-test.js
index dd5a96a988..2704f15767 100644
--- a/src/renderers/dom/__tests__/ReactDOMProduction-test.js
+++ b/src/renderers/dom/__tests__/ReactDOMProduction-test.js
@@ -8,7 +8,6 @@
*
* @emails react-core
*/
-
'use strict';
describe('ReactDOMProduction', function() {
@@ -37,7 +36,7 @@ describe('ReactDOMProduction', function() {
spyOn(console, 'error');
warning(false, 'Do cows go moo?');
- expect(console.error.argsForCall.length).toBe(0);
+ expect(console.error.calls.count()).toBe(0);
});
it('should use prod React', function() {
@@ -46,7 +45,7 @@ describe('ReactDOMProduction', function() {
// no key warning
void {[]}
;
- expect(console.error.argsForCall.length).toBe(0);
+ expect(console.error.calls.count()).toBe(0);
});
it('should handle a simple flow', function() {
@@ -87,4 +86,20 @@ describe('ReactDOMProduction', function() {
expect(container.childNodes.length).toBe(0);
});
+ it('should throw with an error code in production', function() {
+ expect(function() {
+ var Component = React.createClass({
+ render: function() {
+ return ['this is wrong'];
+ },
+ });
+ var container = document.createElement('div');
+ ReactDOM.render(, container);
+ }).toThrowError(
+ 'Minified React error #109; visit ' +
+ 'http://facebook.github.io/react/docs/error-decoder.html?invariant=109&args[]=Component' +
+ ' for the full message or use the non-minified dev environment' +
+ ' for full errors and additional helpful warnings.'
+ );
+ });
});
diff --git a/src/renderers/dom/client/ReactDOMComponentTree.js b/src/renderers/dom/client/ReactDOMComponentTree.js
index ec95b26c63..4d9b8315c8 100644
--- a/src/renderers/dom/client/ReactDOMComponentTree.js
+++ b/src/renderers/dom/client/ReactDOMComponentTree.js
@@ -23,13 +23,13 @@ var internalInstanceKey =
'__reactInternalInstance$' + Math.random().toString(36).slice(2);
/**
- * Drill down (through composites and empty components) until we get a native or
- * native text component.
+ * Drill down (through composites and empty components) until we get a host or
+ * host text component.
*
* This is pretty polymorphic but unavoidable with the current structure we have
* for `_renderedChildren`.
*/
-function getRenderedNativeOrTextFromComponent(component) {
+function getRenderedHostOrTextFromComponent(component) {
var rendered;
while ((rendered = component._renderedComponent)) {
component = rendered;
@@ -38,25 +38,25 @@ function getRenderedNativeOrTextFromComponent(component) {
}
/**
- * Populate `_nativeNode` on the rendered native/text component with the given
+ * Populate `_hostNode` on the rendered host/text component with the given
* DOM node. The passed `inst` can be a composite.
*/
function precacheNode(inst, node) {
- var nativeInst = getRenderedNativeOrTextFromComponent(inst);
- nativeInst._nativeNode = node;
- node[internalInstanceKey] = nativeInst;
+ var hostInst = getRenderedHostOrTextFromComponent(inst);
+ hostInst._hostNode = node;
+ node[internalInstanceKey] = hostInst;
}
function uncacheNode(inst) {
- var node = inst._nativeNode;
+ var node = inst._hostNode;
if (node) {
delete node[internalInstanceKey];
- inst._nativeNode = null;
+ inst._hostNode = null;
}
}
/**
- * Populate `_nativeNode` on each child of `inst`, assuming that the children
+ * Populate `_hostNode` on each child of `inst`, assuming that the children
* match up with the DOM (element) children of `node`.
*
* We cache entire levels at once to avoid an n^2 problem where we access the
@@ -80,7 +80,7 @@ function precacheChildNodes(inst, node) {
continue;
}
var childInst = children[name];
- var childID = getRenderedNativeOrTextFromComponent(childInst)._domID;
+ var childID = getRenderedHostOrTextFromComponent(childInst)._domID;
if (childID == null) {
// We're currently unmounting this child in ReactMultiChild; skip it.
continue;
@@ -143,7 +143,7 @@ function getClosestInstanceFromNode(node) {
*/
function getInstanceFromNode(node) {
var inst = getClosestInstanceFromNode(node);
- if (inst != null && inst._nativeNode === node) {
+ if (inst != null && inst._hostNode === node) {
return inst;
} else {
return null;
@@ -158,32 +158,32 @@ function getNodeFromInstance(inst) {
// Without this first invariant, passing a non-DOM-component triggers the next
// invariant for a missing parent, which is super confusing.
invariant(
- inst._nativeNode !== undefined,
+ inst._hostNode !== undefined,
'getNodeFromInstance: Invalid argument.'
);
- if (inst._nativeNode) {
- return inst._nativeNode;
+ if (inst._hostNode) {
+ return inst._hostNode;
}
// Walk up the tree until we find an ancestor whose DOM node we have cached.
var parents = [];
- while (!inst._nativeNode) {
+ while (!inst._hostNode) {
parents.push(inst);
invariant(
- inst._nativeParent,
+ inst._hostParent,
'React DOM tree root should always have a node reference.'
);
- inst = inst._nativeParent;
+ inst = inst._hostParent;
}
// Now parents contains each ancestor that does *not* have a cached native
// node, and `inst` is the deepest ancestor that does.
for (; parents.length; inst = parents.pop()) {
- precacheChildNodes(inst, inst._nativeNode);
+ precacheChildNodes(inst, inst._hostNode);
}
- return inst._nativeNode;
+ return inst._hostNode;
}
var ReactDOMComponentTree = {
diff --git a/src/renderers/dom/client/ReactDOMTreeTraversal.js b/src/renderers/dom/client/ReactDOMTreeTraversal.js
index c4767736bb..9cbc39f3a2 100644
--- a/src/renderers/dom/client/ReactDOMTreeTraversal.js
+++ b/src/renderers/dom/client/ReactDOMTreeTraversal.js
@@ -18,27 +18,27 @@ var invariant = require('invariant');
* different trees.
*/
function getLowestCommonAncestor(instA, instB) {
- invariant('_nativeNode' in instA, 'getNodeFromInstance: Invalid argument.');
- invariant('_nativeNode' in instB, 'getNodeFromInstance: Invalid argument.');
+ invariant('_hostNode' in instA, 'getNodeFromInstance: Invalid argument.');
+ invariant('_hostNode' in instB, 'getNodeFromInstance: Invalid argument.');
var depthA = 0;
- for (var tempA = instA; tempA; tempA = tempA._nativeParent) {
+ for (var tempA = instA; tempA; tempA = tempA._hostParent) {
depthA++;
}
var depthB = 0;
- for (var tempB = instB; tempB; tempB = tempB._nativeParent) {
+ for (var tempB = instB; tempB; tempB = tempB._hostParent) {
depthB++;
}
// If A is deeper, crawl up.
while (depthA - depthB > 0) {
- instA = instA._nativeParent;
+ instA = instA._hostParent;
depthA--;
}
// If B is deeper, crawl up.
while (depthB - depthA > 0) {
- instB = instB._nativeParent;
+ instB = instB._hostParent;
depthB--;
}
@@ -48,8 +48,8 @@ function getLowestCommonAncestor(instA, instB) {
if (instA === instB) {
return instA;
}
- instA = instA._nativeParent;
- instB = instB._nativeParent;
+ instA = instA._hostParent;
+ instB = instB._hostParent;
}
return null;
}
@@ -58,14 +58,14 @@ function getLowestCommonAncestor(instA, instB) {
* Return if A is an ancestor of B.
*/
function isAncestor(instA, instB) {
- invariant('_nativeNode' in instA, 'isAncestor: Invalid argument.');
- invariant('_nativeNode' in instB, 'isAncestor: Invalid argument.');
+ invariant('_hostNode' in instA, 'isAncestor: Invalid argument.');
+ invariant('_hostNode' in instB, 'isAncestor: Invalid argument.');
while (instB) {
if (instB === instA) {
return true;
}
- instB = instB._nativeParent;
+ instB = instB._hostParent;
}
return false;
}
@@ -74,9 +74,9 @@ function isAncestor(instA, instB) {
* Return the parent instance of the passed-in instance.
*/
function getParentInstance(inst) {
- invariant('_nativeNode' in inst, 'getParentInstance: Invalid argument.');
+ invariant('_hostNode' in inst, 'getParentInstance: Invalid argument.');
- return inst._nativeParent;
+ return inst._hostParent;
}
/**
@@ -86,7 +86,7 @@ function traverseTwoPhase(inst, fn, arg) {
var path = [];
while (inst) {
path.push(inst);
- inst = inst._nativeParent;
+ inst = inst._hostParent;
}
var i;
for (i = path.length; i-- > 0;) {
@@ -109,12 +109,12 @@ function traverseEnterLeave(from, to, fn, argFrom, argTo) {
var pathFrom = [];
while (from && from !== common) {
pathFrom.push(from);
- from = from._nativeParent;
+ from = from._hostParent;
}
var pathTo = [];
while (to && to !== common) {
pathTo.push(to);
- to = to._nativeParent;
+ to = to._hostParent;
}
var i;
for (i = 0; i < pathFrom.length; i++) {
diff --git a/src/renderers/dom/client/ReactEventListener.js b/src/renderers/dom/client/ReactEventListener.js
index bbdbbcf291..be78b7c131 100644
--- a/src/renderers/dom/client/ReactEventListener.js
+++ b/src/renderers/dom/client/ReactEventListener.js
@@ -29,8 +29,8 @@ function findParent(inst) {
// TODO: It may be a good idea to cache this to prevent unnecessary DOM
// traversal, but caching is difficult to do correctly without using a
// mutation observer to listen for all DOM changes.
- while (inst._nativeParent) {
- inst = inst._nativeParent;
+ while (inst._hostParent) {
+ inst = inst._hostParent;
}
var rootNode = ReactDOMComponentTree.getNodeFromInstance(inst);
var container = rootNode.parentNode;
diff --git a/src/renderers/dom/client/ReactMount.js b/src/renderers/dom/client/ReactMount.js
index 6ec60a21fa..5e1827b746 100644
--- a/src/renderers/dom/client/ReactMount.js
+++ b/src/renderers/dom/client/ReactMount.js
@@ -169,7 +169,13 @@ function batchedMountComponentIntoNode(
* @see {ReactMount.unmountComponentAtNode}
*/
function unmountComponentFromNode(instance, container, safely) {
+ if (__DEV__) {
+ ReactInstrumentation.debugTool.onBeginFlush();
+ }
ReactReconciler.unmountComponent(instance, safely);
+ if (__DEV__) {
+ ReactInstrumentation.debugTool.onEndFlush();
+ }
if (container.nodeType === DOC_NODE_TYPE) {
container = container.documentElement;
@@ -195,23 +201,23 @@ function hasNonRootReactChild(container) {
var rootEl = getReactRootElementInContainer(container);
if (rootEl) {
var inst = ReactDOMComponentTree.getInstanceFromNode(rootEl);
- return !!(inst && inst._nativeParent);
+ return !!(inst && inst._hostParent);
}
}
-function getNativeRootInstanceInContainer(container) {
+function getHostRootInstanceInContainer(container) {
var rootEl = getReactRootElementInContainer(container);
- var prevNativeInstance =
+ var prevHostInstance =
rootEl && ReactDOMComponentTree.getInstanceFromNode(rootEl);
return (
- prevNativeInstance && !prevNativeInstance._nativeParent ?
- prevNativeInstance : null
+ prevHostInstance && !prevHostInstance._hostParent ?
+ prevHostInstance : null
);
}
function getTopLevelWrapperInContainer(container) {
- var root = getNativeRootInstanceInContainer(container);
- return root ? root._nativeContainerInfo._topLevelWrapper : null;
+ var root = getHostRootInstanceInContainer(container);
+ return root ? root._hostContainerInfo._topLevelWrapper : null;
}
/**
@@ -701,10 +707,10 @@ var ReactMount = {
}
if (__DEV__) {
- var nativeNode = ReactDOMComponentTree.getInstanceFromNode(container.firstChild);
- if (nativeNode._debugID !== 0) {
- ReactInstrumentation.debugTool.onNativeOperation(
- nativeNode._debugID,
+ var hostNode = ReactDOMComponentTree.getInstanceFromNode(container.firstChild);
+ if (hostNode._debugID !== 0) {
+ ReactInstrumentation.debugTool.onHostOperation(
+ hostNode._debugID,
'mount',
markup.toString()
);
diff --git a/src/renderers/dom/client/ReactReconcileTransaction.js b/src/renderers/dom/client/ReactReconcileTransaction.js
index fedd883bf1..403aa7f2ce 100644
--- a/src/renderers/dom/client/ReactReconcileTransaction.js
+++ b/src/renderers/dom/client/ReactReconcileTransaction.js
@@ -110,7 +110,7 @@ function ReactReconcileTransaction(useCreateElement) {
// `ReactServerRendering`), but server-side uses
// `ReactServerRenderingTransaction` instead. This option is here so that it's
// accessible and defaults to false when `ReactDOMComponent` and
- // `ReactTextComponent` checks it in `mountComponent`.`
+ // `ReactDOMTextComponent` checks it in `mountComponent`.`
this.renderToStaticMarkup = false;
this.reactMountReady = CallbackQueue.getPooled(null);
this.useCreateElement = useCreateElement;
diff --git a/src/renderers/dom/client/__tests__/ReactBrowserEventEmitter-test.js b/src/renderers/dom/client/__tests__/ReactBrowserEventEmitter-test.js
index 9de6b2e8e2..009bc5d223 100644
--- a/src/renderers/dom/client/__tests__/ReactBrowserEventEmitter-test.js
+++ b/src/renderers/dom/client/__tests__/ReactBrowserEventEmitter-test.js
@@ -271,7 +271,7 @@ describe('ReactBrowserEventEmitter', function() {
expect(idCallOrder[0]).toBe(getInternal(CHILD));
expect(idCallOrder[1]).toBe(getInternal(PARENT));
expect(idCallOrder[2]).toBe(getInternal(GRANDPARENT));
- expect(console.error.calls.length).toEqual(0);
+ expect(console.error.calls.count()).toEqual(0);
});
/**
@@ -388,7 +388,7 @@ describe('ReactBrowserEventEmitter', function() {
spyOn(EventListener, 'listen');
ReactBrowserEventEmitter.listenTo(ON_CLICK_KEY, document);
ReactBrowserEventEmitter.listenTo(ON_CLICK_KEY, document);
- expect(EventListener.listen.calls.length).toBe(1);
+ expect(EventListener.listen.calls.count()).toBe(1);
});
it('should work with event plugins without dependencies', function() {
@@ -396,7 +396,7 @@ describe('ReactBrowserEventEmitter', function() {
ReactBrowserEventEmitter.listenTo(ON_CLICK_KEY, document);
- expect(EventListener.listen.argsForCall[0][1]).toBe('click');
+ expect(EventListener.listen.calls.argsFor(0)[1]).toBe('click');
});
it('should work with event plugins with dependencies', function() {
@@ -406,8 +406,8 @@ describe('ReactBrowserEventEmitter', function() {
ReactBrowserEventEmitter.listenTo(ON_CHANGE_KEY, document);
var setEventListeners = [];
- var listenCalls = EventListener.listen.argsForCall;
- var captureCalls = EventListener.capture.argsForCall;
+ var listenCalls = EventListener.listen.calls.allArgs();
+ var captureCalls = EventListener.capture.calls.allArgs();
for (var i = 0; i < listenCalls.length; i++) {
setEventListeners.push(listenCalls[i][1]);
}
diff --git a/src/renderers/dom/client/__tests__/ReactDOM-test.js b/src/renderers/dom/client/__tests__/ReactDOM-test.js
index 9c3cef57f9..4576cf9c8a 100644
--- a/src/renderers/dom/client/__tests__/ReactDOM-test.js
+++ b/src/renderers/dom/client/__tests__/ReactDOM-test.js
@@ -115,7 +115,7 @@ describe('ReactDOM', function() {
spyOn(console, 'error');
var element = React.DOM.div();
expect(element.type).toBe('div');
- expect(console.error.argsForCall.length).toBe(0);
+ expect(console.error.calls.count()).toBe(0);
});
it('throws in render() if the mount callback is not a function', function() {
@@ -133,15 +133,15 @@ describe('ReactDOM', function() {
});
var myDiv = document.createElement('div');
- expect(() => ReactDOM.render(, myDiv, 'no')).toThrow(
+ expect(() => ReactDOM.render(, myDiv, 'no')).toThrowError(
'ReactDOM.render(...): Expected the last optional `callback` argument ' +
'to be a function. Instead received: string.'
);
- expect(() => ReactDOM.render(, myDiv, {})).toThrow(
+ expect(() => ReactDOM.render(, myDiv, {})).toThrowError(
'ReactDOM.render(...): Expected the last optional `callback` argument ' +
'to be a function. Instead received: Object.'
);
- expect(() => ReactDOM.render(, myDiv, new Foo())).toThrow(
+ expect(() => ReactDOM.render(, myDiv, new Foo())).toThrowError(
'ReactDOM.render(...): Expected the last optional `callback` argument ' +
'to be a function. Instead received: Foo (keys: a, b).'
);
@@ -164,15 +164,15 @@ describe('ReactDOM', function() {
var myDiv = document.createElement('div');
ReactDOM.render(, myDiv);
- expect(() => ReactDOM.render(, myDiv, 'no')).toThrow(
+ expect(() => ReactDOM.render(, myDiv, 'no')).toThrowError(
'ReactDOM.render(...): Expected the last optional `callback` argument ' +
'to be a function. Instead received: string.'
);
- expect(() => ReactDOM.render(, myDiv, {})).toThrow(
+ expect(() => ReactDOM.render(, myDiv, {})).toThrowError(
'ReactDOM.render(...): Expected the last optional `callback` argument ' +
'to be a function. Instead received: Object.'
);
- expect(() => ReactDOM.render(, myDiv, new Foo())).toThrow(
+ expect(() => ReactDOM.render(, myDiv, new Foo())).toThrowError(
'ReactDOM.render(...): Expected the last optional `callback` argument ' +
'to be a function. Instead received: Foo (keys: a, b).'
);
diff --git a/src/renderers/dom/client/__tests__/ReactMount-test.js b/src/renderers/dom/client/__tests__/ReactMount-test.js
index 96ca4aef33..b72a26dec5 100644
--- a/src/renderers/dom/client/__tests__/ReactMount-test.js
+++ b/src/renderers/dom/client/__tests__/ReactMount-test.js
@@ -44,7 +44,7 @@ describe('ReactMount', function() {
var nodeArray = document.getElementsByTagName('div');
expect(function() {
ReactDOM.unmountComponentAtNode(nodeArray);
- }).toThrow(
+ }).toThrowError(
'unmountComponentAtNode(...): Target container is not a DOM element.'
);
});
@@ -53,7 +53,7 @@ describe('ReactMount', function() {
it('throws when given a string', function() {
expect(function() {
ReactTestUtils.renderIntoDocument('div');
- }).toThrow(
+ }).toThrowError(
'ReactDOM.render(): Invalid component element. Instead of passing a ' +
'string like \'div\', pass React.createElement(\'div\') or .'
);
@@ -67,7 +67,7 @@ describe('ReactMount', function() {
});
expect(function() {
ReactTestUtils.renderIntoDocument(Component);
- }).toThrow(
+ }).toThrowError(
'ReactDOM.render(): Invalid component element. Instead of passing a ' +
'class like Foo, pass React.createElement(Foo) or .'
);
@@ -133,12 +133,12 @@ describe('ReactMount', function() {
spyOn(console, 'error');
ReactMount.render(, container);
- expect(console.error.calls.length).toBe(1);
+ expect(console.error.calls.count()).toBe(1);
container.innerHTML = ' ' + ReactDOMServer.renderToString();
ReactMount.render(, container);
- expect(console.error.calls.length).toBe(2);
+ expect(console.error.calls.count()).toBe(2);
});
it('should not warn if mounting into non-empty node', function() {
@@ -147,7 +147,7 @@ describe('ReactMount', function() {
spyOn(console, 'error');
ReactMount.render(, container);
- expect(console.error.calls.length).toBe(0);
+ expect(console.error.calls.count()).toBe(0);
});
it('should warn when mounting into document.body', function() {
@@ -157,8 +157,8 @@ describe('ReactMount', function() {
ReactMount.render(, iFrame.contentDocument.body);
- expect(console.error.calls.length).toBe(1);
- expect(console.error.argsForCall[0][0]).toContain(
+ expect(console.error.calls.count()).toBe(1);
+ expect(console.error.calls.argsFor(0)[0]).toContain(
'Rendering components directly into document.body is discouraged'
);
});
@@ -174,8 +174,8 @@ describe('ReactMount', function() {
This markup contains an nbsp entity: client text
,
div
);
- expect(console.error.calls.length).toBe(1);
- expect(console.error.argsForCall[0][0]).toContain(
+ expect(console.error.calls.count()).toBe(1);
+ expect(console.error.calls.argsFor(0)[0]).toContain(
' (client) nbsp entity: client text \n' +
' (server) nbsp entity: server text'
);
@@ -217,8 +217,8 @@ describe('ReactMount', function() {
spyOn(console, 'error');
var rootNode = container.firstChild;
ReactDOM.render(