Skip to content

Commit

Permalink
RN: Refactor MockNativeMethods in Jest
Browse files Browse the repository at this point in the history
Reviewed By: sahrens

Differential Revision: D7917498

fbshipit-source-id: 97636080588bf2641a56256688cb0f2ec81ae463
  • Loading branch information
yungsters authored and facebook-github-bot committed May 9, 2018
1 parent 67dbcbd commit 5d4c542
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 26 deletions.
38 changes: 38 additions & 0 deletions jest/MockNativeMethods.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/

'use strict';

const mockNativeFunction = methodName => {
let warned = false;
return function() {
if (warned) {
return;
}
warned = true;
console.warn(
'Calling .' +
methodName +
'() in the test renderer environment is not supported. Instead, mock ' +
'out your components that use findNodeHandle with replacements that ' +
"don't rely on the native environment.",
);
};
};

const MockNativeMethods = {
measure: mockNativeFunction('measure'),
measureInWindow: mockNativeFunction('measureInWindow'),
measureLayout: mockNativeFunction('measureLayout'),
setNativeProps: mockNativeFunction('setNativeProps'),
focus: mockNativeFunction('focus'),
blur: mockNativeFunction('blur'),
};

module.exports = MockNativeMethods;
29 changes: 3 additions & 26 deletions jest/setup.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
*/
'use strict';

const MockNativeMethods = require.requireActual('./MockNativeMethods');
const mockComponent = require.requireActual('./mockComponent');

require.requireActual('../Libraries/polyfills/babelHelpers.js');
Expand Down Expand Up @@ -81,33 +82,9 @@ jest
const NativeMethodsMixin =
ReactNative.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.NativeMethodsMixin;

const mockFunction = (key) => {
let warned = false;
return function() {
if (warned) {
return;
}
warned = true;
console.warn(
'Calling .' + key + '() in the test renderer environment is not ' +
'supported. Instead, mock out your components that use ' +
'findNodeHandle with replacements that don\'t rely on the ' +
'native environment.',
);
};
};
Object.assign(NativeMethodsMixin, MockNativeMethods);
Object.assign(ReactNative.NativeComponent.prototype, MockNativeMethods);

[
'measure',
'measureInWindow',
'measureLayout',
'setNativeProps',
'focus',
'blur',
].forEach((key) => {
NativeMethodsMixin[key] = mockFunction(key);
ReactNative.NativeComponent.prototype[key] = mockFunction(key);
});
return ReactNative;
})
.mock('ensureComponentIsNative', () => () => true);
Expand Down

0 comments on commit 5d4c542

Please sign in to comment.