Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[HOLD][No QA] Add automated tests for Report actions/ Pusher #771

Closed
wants to merge 9 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"ios-build": "fastlane ios build",
"android-build": "fastlane android build",
"test": "jest",
"lint-tests": "eslint tests/**",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are we separating out linting tests and the source? Ideally they are the same, right?

"lint": "eslint . --config config/.eslintrc.js",
"postversion": "react-native-version",
"print-version": "echo $npm_package_version",
Expand Down Expand Up @@ -106,6 +107,7 @@
"jest-circus": "^26.5.2",
"jest-cli": "^26.5.2",
"metro-react-native-babel-preset": "^0.61.0",
"pusher-js-mock": "^0.3.3",
"react-hot-loader": "^4.12.21",
"react-native-version": "^4.0.0",
"react-test-renderer": "16.13.1",
Expand Down
1 change: 1 addition & 0 deletions src/CONFIG.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ export default {
},
// eslint-disable-next-line no-undef
IS_IN_PRODUCTION: Platform.OS === 'web' ? process.env.NODE_ENV === 'production' : !__DEV__,
IS_JEST_RUNNING: typeof jest !== 'undefined',
PUSHER: {
APP_KEY: Config.PUSHER_APP_KEY,
CLUSTER: 'mt1',
Expand Down
6 changes: 6 additions & 0 deletions src/libs/Network.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import Onyx from 'react-native-onyx';
import HttpUtils from './HttpUtils';
import NetworkConnection from './NetworkConnection';
import ONYXKEYS from '../ONYXKEYS';
import CONFIG from '../CONFIG';

let isQueuePaused = false;

Expand Down Expand Up @@ -74,6 +75,11 @@ setInterval(processNetworkRequestQueue, 1000);
* @returns {Promise}
*/
function post(command, data, type) {
// Mock all post requests
if (CONFIG.IS_JEST_RUNNING) {
return Promise.resolve();
}

return new Promise((resolve, reject) => {
// Add the write request to a queue of actions to perform
networkRequestQueue.push({
Expand Down
10 changes: 9 additions & 1 deletion src/libs/actions/Report.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import Visibility from '../Visibility';
import ROUTES from '../../ROUTES';
import NetworkConnection from '../NetworkConnection';
import {hide as hideSidebar} from './Sidebar';
import CONFIG from '../../CONFIG';
import * as API from '../API';

let currentUserEmail;
Expand Down Expand Up @@ -281,7 +282,14 @@ function subscribeToReportCommentEvents() {
}

const pusherChannelName = `private-user-accountID-${currentUserAccountID}`;
if (Pusher.isSubscribed(pusherChannelName) || Pusher.isAlreadySubscribing(pusherChannelName)) {

const pusherSubscribedOrSubscribing = Pusher.isSubscribed(pusherChannelName)
|| Pusher.isAlreadySubscribing(pusherChannelName);

// This check is to prevent duplicate subscriptions. The mock channels for jest
// are always subscribed when created so we skip this check when testing or else it
// will prevent us from binding an even to the channel.
if (!CONFIG.IS_JEST_RUNNING && pusherSubscribedOrSubscribing) {
return;
}

Expand Down
130 changes: 130 additions & 0 deletions tests/unit/reportActionTest.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
import moment from 'moment';
import Onyx from 'react-native-onyx';
import ONYXKEYS from '../../src/ONYXKEYS';
import {addAction, subscribeToReportCommentEvents} from '../../src/libs/actions/Report';
import * as Pusher from '../../src/libs/Pusher/pusher';

const resolveAllPromises = () => new Promise(setImmediate);

Onyx.registerLogger(() => {});
Onyx.init({
keys: ONYXKEYS,
registerStorageEventListener: () => {},
});

jest.mock('../../node_modules/urbanairship-react-native', () => {
const airshipMock = require('./mocks/urbanairship-react-native');
airshipMock.EventType = {
PushReceived: 'pushReceived',
};
return airshipMock;
});

jest.mock('../../node_modules/@react-native-community/async-storage', () => (
require('./mocks/@react-native-community/async-storage')
));

jest.mock('../../node_modules/@react-native-community/push-notification-ios', () => (
require('./mocks/@react-native-community/push-notification-ios')
));

jest.mock('pusher-js/react-native', () => (
require('pusher-js-mock').PusherMock
));

jest.mock('../../node_modules/@react-native-community/netinfo', () => (
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm curious if we'd prefer to put all these mocks in a different file and then import them? It might DRY up the tests a bit.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll try to get this working.

require('./mocks/@react-native-community/netinfo')
));

describe('Report Action', () => {
it('should subscribe to the private-user-accountID channel', async (done) => {
const reportID = 1;
const CREATED_ACTION = {
actionName: 'CREATED',
automatic: false,
created: 'Oct 28 2020 4:29pm PDT',
message: [
{type: 'TEXT', style: 'strong', text: '__fake__'},
{type: 'TEXT', style: 'normal', text: ' created this report'},
],
person: [{type: 'TEXT', style: 'strong', text: '__fake__'}],
sequenceNumber: 0,
shouldShow: true,
timestamp: 1604682894,
};

const mockOnyxCallback = jest.fn();

Pusher.init();

// Set up fake accountID, email, and reportActions key
await Onyx.set(ONYXKEYS.SESSION, {accountID: 1, email: 'test@test.com'});
await Onyx.set(ONYXKEYS.MY_PERSONAL_DETAILS, {});

// Simulate fetching a brand new report and actions
await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, {
reportID,
reportName: 'Test User',
});

await Onyx.set(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`, {
[CREATED_ACTION.sequenceNumber]: CREATED_ACTION,
});

Onyx.connect({
key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${reportID}`,
initWithStoredValues: false,
callback: (val) => {
try {
mockOnyxCallback(val);

// Verify that the optimistic comment has a loading state
if (mockOnyxCallback.mock.calls.length === 1) {
expect(val[0]).toStrictEqual(CREATED_ACTION);
expect(val[1]).toBeTruthy();
expect(val[1].loading).toBe(true);
return;
}

// Verify the loading state is now false
expect(val[1].loading).toBe(false);
done();
} catch (err) {
done(err);
}
},
});

subscribeToReportCommentEvents();
const PRIVATE_USER_CHANNEL = 'private-user-accountID-1';
const isSubscribedToPrivateChannel = Pusher.isSubscribed(PRIVATE_USER_CHANNEL);
expect(isSubscribedToPrivateChannel).toBe(true);

// Add an action
addAction(reportID, 'Testing a comment');

// We have to resolve all the promises here otherwise we will end up
// handling the mock pusher payload before the optimistic comment set in
// addAction()
await resolveAllPromises();

// Simulate handling the comment push event from the server
const testReportCommentPusherPayload = {
reportID,
reportAction: {
actionName: 'ADDCOMMENT',
automatic: false,
created: 'Nov 6 2020 9:14am PST',
message: [{type: 'COMMENT', html: 'Testing a comment', text: 'Testing a comment'}],
person: [{type: 'TEXT', style: 'strong', text: 'Test User'}],
shouldShow: true,
timestamp: moment().unix(),
actorAccountID: 1,
sequenceNumber: 1,
},
};

const channel = Pusher.getChannel(PRIVATE_USER_CHANNEL);
channel.emit('reportComment', testReportCommentPusherPayload);
});
});