Summary:
`Jest` allows to use fake timers and according to https://developer.mozilla.org/en-US/docs/Web/API/Window/requestAnimationFrame the return value should be `A long integer value, the request id, that uniquely identifies the entry in the callback list`. This allows to use `cancelAnimationFrame`.
In current implementation of `jest/setup.js`, the return value is undefined. Therefore it's not possible to cancel the animation frame request.
```
let id = null;
const registerCallback = (callback) => {
clearCallback();
id = requestAnimationFrame(() => {
id = null;
callback();
});
};
const clearCallback = () => {
if (null !== id) {
cancelAnimationFrame(id);
id = null;
}
};
```
```
jest.useFakeTimers();
const callback = jest.fn();
registerCallback(callback);
clearCallback();
jest.runAllTimers();
expect(callback).toHaveBeenCalledTimes(0); // Will be error in current implementation, since nothing is cleared. And test will pass, after MR is merged
```
This is fake example, but the real usage is when the animation frame request should be removed on `ComponentWillUnmount`.
[JEST] [BUGFIX] [requestAnimationFrame] - return request id
Closes https://github.com/facebook/react-native/pull/16367
Differential Revision: D6060578
Pulled By: ericnakagawa
fbshipit-source-id: c785a3380f5e267b48ae16fcf34dbbf95fa54178
Summary:
When Jest is mocking native components that are assigned a ref with an arrow function, a warning is generated about stateless components which can not have a ref. This does not happen when the ref is assigned directly.
Fixes#16045.
<!--
Thank you for sending the PR! We appreciate you spending the time to work on these changes.
Help us understand your motivation by explaining why you decided to make this change.
You can learn more about contributing to React Native here: http://facebook.github.io/react-native/docs/contributing.html
Happy contributing!
-->
The test provided in the related issue is used to validate the fix. I don't know how to detect console warnings in a Jest test.
Closes https://github.com/facebook/react-native/pull/16046
Differential Revision: D6017903
Pulled By: ericnakagawa
fbshipit-source-id: a7ed61c39f141a4094f08fc875289a7a79ebe9e8
Summary:
Basic implementation of the proposal in #15271
Note that this should not affect facebook internally since they are not using OSS releases.
Points to consider:
- How strict should the version match be, right now I just match exact versions.
- Wasn't able to use haste for ReactNativeVersion because I was getting duplicate module provider caused by the template file in scripts/versiontemplates. I tried adding the scripts folder to modulePathIgnorePatterns in package.json but that didn't help.
- Redscreen vs. warning, I think warning is useless because if the app crashes you won't have time to see the warning.
- Should the check and native modules be __DEV__ only?
**Test plan**
Tested that it works when version match and that it redscreens when versions don't before getting other errors on Android and iOS.
Closes https://github.com/facebook/react-native/pull/15518
Differential Revision: D5813551
Pulled By: hramos
fbshipit-source-id: 901757e25724b0f22bf39de172b56309d0dd5a95
Summary:
React Native v0.48.0 shipped `WebSocketModule` support with `BlobModule` as dependency. But `BlobModule` is not mocked in jest which will cause render tests failed.
Reference implantation: [BlobModule.java](ed903099b4/ReactAndroid/src/main/java/com/facebook/react/modules/blob/BlobModule.java)
Related PR: #11417
Related issue: #15810
Passed CI tests.
Need render a component in jest with WebSocketModule as dependency.
Closes https://github.com/facebook/react-native/pull/15843
Differential Revision: D5783263
Pulled By: shergin
fbshipit-source-id: 2386692f4a644796da2fd66b3135da9f5911663e
Summary:
This change only affects tests run with Jest. `require('/images/image1.png')` will be replaced with
```
Object {
"testUri": "relative/path/to/images/image1.png",
}
```
in the Jest snapshot instead of always being 1 returned by RelativeImageStub. This change makes it possible to test conditional asset loading in components.
The problem with this change is that it will probably break a lot of existing snapshots, but that should be easily fixed when a project updates to a new version of React Native by running `jest -u` to update all snapshots.
A component can have conditional asset loading based on its props, this logic would be nice to test with Jest snapshots. This problem has been discussed in https://github.com/facebook/jest/issues/2838.
* **Who does this affect**: Everyone using `Image` in Jest snapshots
* **How to migrate**: Running `jest -u` will update the snapshots, the snapshots should be reviewed that they are correct.
* **Why make this breaking change**: It enables testing of conditional asset loading.
* **Severity (number of people affected x effort)**: Low.
Closes https://github.com/facebook/react-native/pull/13319
Reviewed By: rafeca
Differential Revision: D5708180
Pulled By: mjesun
fbshipit-source-id: 16ac42004d597db08545a21d4fffe95c5ee7e21f
Summary:
This isn't exhaustive, but it's a few more functions that these modules normally export which need to be stubbed.
Closes https://github.com/facebook/react-native/pull/14432
Differential Revision: D5345928
Pulled By: shergin
fbshipit-source-id: f333056ac43ce7c75c6734bca8dc9035745721df
Summary: Upgrade metro-bundler to v0.9.0. This version has no functional change. The only change is that the structure of the npm package reflects the structure of the source code.
Reviewed By: bestander
Differential Revision: D5315651
fbshipit-source-id: 3a69337106d4ccf708823c80d304941973360e8e
Summary:
`retainLines` is no longer necessary with the much improved source map generation.
`sourceMaps` is handled by the transformer itself.
Reviewed By: cpojer
Differential Revision: D5237103
fbshipit-source-id: e5c6bf5aa9d553fce9c3f4d59b3ea0057d45cfdc
Summary: This folder is not necessary any longer. All the code now lives in https://github.com/facebook/metro-bundler
Reviewed By: davidaurelio, jeanlauliac
Differential Revision: D5199196
fbshipit-source-id: 35bf0f10a9163f53426db9a76f8f853dceb69167
Summary:
When trying to mock an Image on Android, this error occurs referencing the ImageLoader mock in setup.js:
```
/Users/.../node_modules/react-native/jest/setup.js:120
return success(320,240);
^
TypeError: success is not a function
at /Users/.../node_modules/react-native/jest/setup.js:120:8
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)
```
- Mocking Images works for iOS but not Android.
- Since Image.android.js uses ImageLoader vs ImageViewManager, the code cannot be carried over from iOS.
Since this is code within the testing framework, the existing tests should test this. If there is no existing test coverage, then this would need to be done.
Closes https://github.com/facebook/react-native/pull/14262
Differential Revision: D5162640
Pulled By: shergin
fbshipit-source-id: 5b1efbbb685b767e09b5c7fb05f073445c94a3aa
Summary:
Pass `localPath` to transformers to allow usage of plugins like `transform-react-jsx-source` that don’t conflict with x-machine caches, e.g. Buck or our own global cache.
These caches don’t work properly if paths local to a specific machine are part of cached outputs.
Reviewed By: jeanlauliac
Differential Revision: D5044147
fbshipit-source-id: 1177afb48d6dd9351738fcd4da8f9f6357e25e81
Summary:
`PushNotificationIOS` is a library that makes use of the
`PushNotificationManager` native module.
This commit adds a jest mock for its native module so that code that
uses `PushNotificationIOS` can be tested using jest.
In order to enable behaviour in unit tests it is possible to replace or
overwrite the mock implementation, see the [jest guide on
mocks](https://facebook.github.io/jest/docs/mock-functions.html).
By doing something similar to:
```javascript
import { NativeModules } from 'react-native';
const { PushNotificationManager } = NativeModules;
// mock 'checkPermissions' to return a different value than the default:
PushNotificationManager.checkPermissions.mockImplementationOnce((callback) => {
// execute callback in next tick to enable async behaviour
process.nextTick(() => callback({
alert: false,
badge: false,
sound: false
}));
});
// execute unit tests for code that makes use of 'PushNotificationIOS'
```
Closes https://github.com/facebook/react-native/pull/13410
Differential Revision: D5043904
Pulled By: cpojer
fbshipit-source-id: 11e73cd215ba6854d06f4ac7a5aea0ab4be26584
Summary:
Hello!
The [Geolocation API](https://facebook.github.io/react-native/docs/geolocation.html) is currently not mocked in Jest, which often leads to an `Invariant Violation: Native module cannot be null` error. This patch adds a basic Jest configuration similar to the existing ones for the other modules.
None unfortunately, but this patch makes my test suite all green 😉
Thanks,
William
Closes https://github.com/facebook/react-native/pull/13442
Differential Revision: D4883830
Pulled By: javache
fbshipit-source-id: c2a976834cca7537bd832a698e8cd25cf877705b
Summary:
The current mock of `AsyncLocalStorage` seems to mock parts of the
`AsyncStorage` API that can't be found on the `AsyncLocalStorage`
object itself and therefore it doesn't work as expected.
What it should do is mock the API of `AsyncLocalStorage` which is a
`NativeModule` so that the `AsyncStorage` module can be used in tests
and it will require the mocked methods.
In order to enable behaviour in unit tests it is possible to replace or
overwrite the mock implementation, see the [jest guide on mocks](https://facebook.github.io/jest/docs/mock-functions.html).
By doing something similar to:
```javascript
import { NativeModules } from 'react-native';
const { AsyncLocalStorage } = NativeModules;
// mock 'multiGet', in order to allow 'AsyncStorage.getItem('myKey')'
AsyncLocalStorage.multiGet.mockImplementationOnce((keys, callback) => {
callback(null, [['myKey', 'myValue']]);
});
// execute unit tests for code that makes use of 'AsyncStorage'
```
Closes https://github.com/facebook/react-native/pull/13433
Differential Revision: D4883389
Pulled By: javache
fbshipit-source-id: 92a0ee94480b3022acc748e306ee2d4ee7a9869d
Summary:
The `UIManager` already has a lot of responsibilities and is deeply
tied with React Native's view architecture. This diff separates out a
`DeviceInfo` native module to provide information about screen dimensions and
font scale, etc.
Reviewed By: fkgozali
Differential Revision: D4713834
fbshipit-source-id: f2ee93acf876a4221c29a8c731f5abeffbb97974
Summary:
This moves the `src` directory one level up and removes the `react-packager` folder. Personally, I always disliked this indirection. I'm reorganizing some things in RNP, so this seems to make sense.
Not sure if I forgot to update any paths. Can anyone advice if there are more places that need change?
Reviewed By: jeanlauliac
Differential Revision: D4487867
fbshipit-source-id: d63f9c79d6238300df9632d2e6a4e6a4196d5ccb
Summary:
Introduces a new mechanism to build source maps that allows us to use real mapping segments instead of just mapping line-by-line.
This mechanism is only used when building development bundles to improve the debugging experience in Chrome.
The new mechanism takes advantage of a new feature in babel-generator that exposes raw mapping objects. These raw mapping objects are converted to arrays with 2, 4, or 5 for the most compact representation possible.
We no longer generate a source map for the bundle that maps each line to itself in conjunction with configuring babel generator to retain lines.
Instead, we create a source map with a large mappings object produced from the mappings of each individual file in conjunction with a “carry over” – the number of preceding lines in the bundle.
The implementation makes a couple of assumptions that hold true for babel transform results, e.g. mappings being in the order of the generated code, and that a block of mappings always belongs to the same source file. In addition, the implementation avoids allocation of objects and strings at all costs. All calculations are purely numeric, and base64 vlq produces numeric ascii character codes. These are written to a preallocated buffer objects, which is turned to a string only at the end of the building process. This implementation is ~5x faster than using the source-map library.
In addition to providing development source maps that work better, we can now also produce individual high-quality source maps for production builds and combine them to an “index source map”. This approach is unfeasable for development source maps, because index source map consistently crash Chrome.
Better production source maps are useful to get precise information about source location and symbol names when symbolicating stack traces from crashes in production.
Reviewed By: jeanlauliac
Differential Revision: D4382290
fbshipit-source-id: 365a176fa142729d0a4cef43edeb81084361e54d
Summary:
Currently the jest mock for `ListViewDataSource` has a property called `items` which returns the number of items of the data source. Example from a snapshot:
ListViewDataSource {
"items": 6,
}
If the datablob includes immutable Maps like:
const dataBlob = {
'alpha': immutable.Map({ name: 'Alpha' }),
'beta': immutable.Map({ name: 'Beta' }),
};
then the result is:
ListViewDataSource {
"items": NaN,
}
This PR checks if the properties of the `dataBlob` are immutable Maps and then checks whether they are empty.
The result for the above dataBlob would be:
ListViewDataSource {
"items": 2,
}
Closes https://github.com/facebook/react-native/pull/11567
Differential Revision: D4354977
Pulled By: cpojer
fbshipit-source-id: 9f6bd6ea9896eebd9373344a43ffe97deee5015b
Summary:
`Fake` components are simplified so snapshots are stable and reliable, and references are exported
so that interactions like `onRefresh` and `onScroll` can be called manually. Currently there is just
one global export for each class, but we may change this in the future if we need to manage multiple
`Fake`s of the same type in one render tree.
Right now these must be installed explicitly, but I might move them into `__mocks__` folders if it
seems reasonable to make them defaults.
Reviewed By: cpojer
Differential Revision: D4318207
fbshipit-source-id: 62802353a98b09ca1c80804ef7201ea63091f94a
Summary:
**Description:**
Jest tests that use that StatusBar failing because the status bar functions aren't mocked.
Errors I ran into:
`TypeError: StatusBarManager. setNetworkActivityIndicatorVisible is not a function`
`TypeError: StatusBarManager. setHidden is not a function`
`TypeError: StatusBarManager. setStyle is not a function`
**Fix:**
Added mocks for all the functions that the StatusBar offers according to the docs: https://facebook.github.io/react-native/docs/statusbar.html
**Test plan (required)**
Verify that the tests using StatusBar and its functions succeed.
Closes https://github.com/facebook/react-native/pull/11322
Differential Revision: D4284536
Pulled By: cpojer
fbshipit-source-id: b67be8c0595d91ee9aca4784f457c0959d7e45d5
Summary:
Fix an issue when running Jest unit tests due to a missing mock for StatusBarManger.
**More info:**
In one of my files I have:
```
export const STATUS_BAR_HEIGHT = (StatusBar.currentHeight || 0);
```
When I run the tests it gives this error, which seems to be because StatusBarManager is undefined (https://github.com/facebook/react-native/blob/master/Libraries/Components/StatusBar/StatusBar.js#L20)
```
TypeError: Cannot read property 'HEIGHT' of undefined
at Object.<anonymous> (node_modules/react-native/Libraries/Components/StatusBar/StatusBar.js:395:1823)
at Object.StatusBar (node_modules/react-native/Libraries/react-native/react-native.js:55:24)
```
**Test plan (required)**
Verify that with this change tests that use StatusBar pass.
Closes https://github.com/facebook/react-native/pull/11198
Differential Revision: D4246367
Pulled By: cpojer
fbshipit-source-id: ee9406d2566688d235a11cab8f24b0583698e93a
Summary:
**Description**
In the same vein as https://github.com/facebook/react-native/pull/11198, this adds a mock for the native module `AppState`.
**Test plan**
Create a component that uses `AppState`, e.g.
```jsx
import React, { Component } from 'react';
import { AppState } from 'react-native';
class TestComponent extends Component {
componentDidMount() {
AppState.addEventListener('change', this.stateChangeListener);
}
}
```
Closes https://github.com/facebook/react-native/pull/11199
Differential Revision: D4246668
Pulled By: cpojer
fbshipit-source-id: e3a73a98963a0e152a70aba78ef3461b86da0f6c
Summary:
Fixes warnings such as `Warning: Native component for "RCTView" does not exist` when you don't mock the native view class on `UIManager`.
**Test plan (required)**
Run `npm test` with it and without it, notice that warnings are gone and results are the same.
cc cpojer
Closes https://github.com/facebook/react-native/pull/10486
Differential Revision: D4063500
Pulled By: cpojer
fbshipit-source-id: f6bdda1fdd1ad87958f435071d353684cb812af4