Skip to content

Commit

Permalink
Refactor fetch mock
Browse files Browse the repository at this point in the history
  • Loading branch information
roryabraham committed Apr 21, 2023
1 parent c858075 commit 9176a17
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 46 deletions.
13 changes: 6 additions & 7 deletions tests/actions/IOUTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,10 @@ describe('actions/IOU', () => {
Onyx.init({
keys: ONYXKEYS,
});
global.fetch = TestHelper.getOnDemandFetchMock();
// global.fetch = TestHelper.getGlobalFetchMock();
});

beforeEach(() => {
// jest.resetAllMocks();
global.fetch = TestHelper.getGlobalFetchMock();
return Onyx.clear().then(waitForPromisesToResolve);
});

Expand All @@ -31,12 +29,13 @@ describe('actions/IOU', () => {
it('creates new chat if needed', () => {
const amount = 100;
const comment = 'Giv money plz';
IOU.requestMoney({}, amount, CONST.CURRENCY.USD, RORY_EMAIL, {login: CARLOS_EMAIL}, comment);
let chatReportID;
let iouReportID;
let createdAction;
let iouAction;
let transactionID;
fetch.pause();
IOU.requestMoney({}, amount, CONST.CURRENCY.USD, RORY_EMAIL, {login: CARLOS_EMAIL}, comment);
return waitForPromisesToResolve()
.then(() => new Promise((resolve) => {
const connectionID = Onyx.connect({
Expand Down Expand Up @@ -122,15 +121,15 @@ describe('actions/IOU', () => {
},
});
}))
.then(fetch.flush)
.then(fetch.resume)
.then(() => new Promise((resolve) => {
const connectionID = Onyx.connect({
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${chatReportID}`,
waitForCollectionCallback: true,
callback: reportActionsForChatReport => {
Onyx.disconnect(connectionID);
expect(_.size(reportActionsForChatReport)).toBe(2);
_.each(reportActionsForChatReport, reportAction => expect(reportAction.pendingAction).not.toBeTruthy());
_.each(reportActionsForChatReport, reportAction => expect(reportAction.pendingAction).toBeFalsy());
resolve();
},
});
Expand All @@ -141,7 +140,7 @@ describe('actions/IOU', () => {
waitForCollectionCallback: true,
callback: transaction => {
Onyx.disconnect(connectionID);
expect(transaction.pendingAction).not.toBeTruthy();
expect(transaction.pendingAction).toBeFalsy();
resolve();
},
});
Expand Down
70 changes: 31 additions & 39 deletions tests/utils/TestHelper.js
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,13 @@ function signOutTestUser() {
/**
* Use for situations where fetch() is required.
*
* It also has some additional methods:
*
* - pause() – stop resolving promises until you call resume()
* - resume() - flush the queue of promises, and start resolving new promises immediately
* - fail() - start returning a failure response
* - success() - go back to returning a success response
*
* @example
*
* beforeAll(() => {
Expand All @@ -146,50 +153,36 @@ function signOutTestUser() {
* @returns {Function}
*/
function getGlobalFetchMock() {
return jest.fn()
.mockResolvedValue({
let queue = [];
let isPaused = false;
let shouldFail = false;

const getResponse = () => shouldFail
? {ok: false}
: {
ok: true,
json: () => Promise.resolve({
jsonCode: 200,
jsonCode: 200
}),
});
}
};

/**
* Mocks fetch, but requests won't resolve until you call `flush` on the object returned by this function.
*
* @example
*
* beforeAll(() => {
* global.fetch = TestHelper.getOnDemandFetchMock();
* })
*
* it("doesn't reply to fetch until you tell it to", () => {
* const myRequest = fetch('something');
*
* // Make some assertion that will only be true before your request resolves
*
* fetch.flush()
* .then(() => {
* // Make some assertion that will only be true after your request resolves
* });
* })
* @returns {Function}
*/
function getOnDemandFetchMock() {
let queue = [];
const mockFetch = jest.fn().mockImplementation(() => new Promise(resolve => queue.push(resolve)));
mockFetch.flush = () => {
_.each(queue, resolve => {
resolve({
ok: true,
json: () => Promise.resolve({
jsonCode: 200,
}),
});
const mockFetch = jest.fn()
.mockImplementation(() => {
if (!isPaused) {
return Promise.resolve(getResponse());
}
return new Promise(resolve => queue.push(resolve));
});

mockFetch.pause = () => isPaused = true;
mockFetch.resume = () => {
isPaused = false;
_.each(queue, resolve => resolve(getResponse()));
return waitForPromisesToResolve();
}
};
mockFetch.fail = () => shouldFail = true;
mockFetch.succeed = () => shouldFail = false;

return mockFetch;
}

Expand Down Expand Up @@ -227,7 +220,6 @@ function buildTestReportComment(actorEmail, created, actorAccountID, actionID =

export {
getGlobalFetchMock,
getOnDemandFetchMock,
signInWithTestUser,
signOutTestUser,
setPersonalDetails,
Expand Down

0 comments on commit 9176a17

Please sign in to comment.