You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This repository illustrates how to use [Mock Service Worker](https://github.com/mswjs/msw) to mock a REST API for development, unit and E2E testing in a project initiated with `npx react-native init MSWReactNative --template react-native-template-typescript`.
-[Jest](https://jestjs.io) for running unit tests;
9
+
-[React Native Testing Library](https://github.com/callstack/react-native-testing-library) for unit test assertions;
10
+
-[Detox](https://github.com/wix/Detox) for running E2E tests;
11
+
12
+
## Getting started
13
+
14
+
```bash
15
+
$ git clone https://github.com/mswjs/examples.git
16
+
$ cd examples
17
+
$ yarn
18
+
$ cd rest-react-native
19
+
$ yarn pods
20
+
```
21
+
22
+
## Running locally
23
+
24
+
```bash
25
+
$ yarn start
26
+
```
27
+
28
+
## Tests
29
+
30
+
### Unit tests
31
+
32
+
```bash
33
+
$ yarn test:unit
34
+
```
35
+
36
+
### E2E tests
37
+
38
+
```bash
39
+
$ yarn test:e2e
40
+
```
41
+
42
+
## Key points
43
+
44
+
- The polyfill `react-native-url-polyfill` is required or else calling `server.start()` will result in an Error: not implemented message followed by Error: Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication)... due to the barebones React Native URL polyfill that throws Not Implemented exceptions for functions that MSW calls such as [search()](https://github.com/facebook/react-native/blob/cd347a7e0ed29ae1049e041fcb34588e1aac76f9/Libraries/Blob/URL.js#L194).
45
+
- Absolute paths must be used for handlers on React Native, otherwise `TypeError: undefined is not an object (evaluating 'window.location.href')` is raised.
46
+
-[`src/api/mocks/handlers.ts`](src/api/mocks/handlers.ts) describes request handlers to use.
47
+
48
+
### React Native
49
+
50
+
-[`src/api/mocks/server.ts`](src/api/mocks/server.ts) sets up the React Native server.
51
+
-[`./index.js`](./index.js) conditionally enables mocking in `development` environment.
52
+
53
+
### NodeJS
54
+
55
+
-[`src/api/mocks/testServer.ts`](src/api/mocks/testServer.ts) sets up the Node server to use the same mocking logic in Node as React Native.
56
+
-[`./setupJest.ts`](./setupJest.ts) enables mocking for unit tests via `beforeAll`/`afterAll` hooks and adds `node-fetch` to the `global` scope.
0 commit comments