forked from Expensify/App
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RequestTest.js
62 lines (52 loc) · 2.02 KB
/
RequestTest.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import * as Request from '../../src/libs/Request';
import waitForPromisesToResolve from '../utils/waitForPromisesToResolve';
import * as TestHelper from '../utils/TestHelper';
beforeAll(() => {
global.fetch = TestHelper.getGlobalFetchMock();
});
beforeEach(() => {
Request.clearMiddlewares();
});
test('Request.use() can register a middleware and it will run', () => {
const testMiddleware = jest.fn();
Request.use(testMiddleware);
const request = {
command: 'MockCommand',
data: {authToken: 'testToken', persist: true},
};
Request.processWithMiddleware(request, true);
return waitForPromisesToResolve()
.then(() => {
const [promise, returnedRequest, isFromSequentialQueue] = testMiddleware.mock.calls[0];
expect(testMiddleware).toHaveBeenCalled();
expect(returnedRequest).toEqual(request);
expect(isFromSequentialQueue).toBe(true);
expect(promise).toBeInstanceOf(Promise);
});
});
test('Request.use() can register two middlewares. They can pass a response to the next and throw errors', () => {
// Given an initial middleware that returns a promise with a resolved value
const testMiddleware = jest.fn().mockResolvedValue({
jsonCode: 404,
});
// And another middleware that will throw when it sees this jsonCode
const errorThrowingMiddleware = promise => promise.then(response => new Promise((resolve, reject) => {
if (response.jsonCode !== 404) {
return;
}
reject(new Error('Oops'));
}));
Request.use(testMiddleware);
Request.use(errorThrowingMiddleware);
const request = {
command: 'MockCommand',
data: {authToken: 'testToken'},
};
const catchHandler = jest.fn();
Request.processWithMiddleware(request).catch(catchHandler);
return waitForPromisesToResolve()
.then(() => {
expect(catchHandler).toHaveBeenCalled();
expect(catchHandler).toHaveBeenCalledWith(new Error('Oops'));
});
});