Skip to content

Commit

Permalink
chore: add jest integration
Browse files Browse the repository at this point in the history
chore: add unit test for summit actions
chore: add unit test for summit forms
  • Loading branch information
smarcet committed May 1, 2024
1 parent 15f00f3 commit 3261dec
Show file tree
Hide file tree
Showing 11 changed files with 4,976 additions and 3,252 deletions.
15 changes: 15 additions & 0 deletions .github/workflows/jest.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
name: jest

on: [push, pull_request]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- uses: actions/setup-node@v3
with:
node-version: 18
- run: yarn install
- run: yarn test
2 changes: 1 addition & 1 deletion .nvmrc
Original file line number Diff line number Diff line change
@@ -1 +1 @@
16.17.0
18.20.2
14 changes: 14 additions & 0 deletions babel.config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"presets": [
"@babel/preset-env",
[
"@babel/preset-react",
{
"runtime": "automatic"
}
]
],
"plugins": [
[ "@babel/plugin-transform-runtime", { "regenerator": true } ]
]
}
59 changes: 57 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
"build-dev": "./node_modules/.bin/webpack --config webpack.dev.js",
"build": "./node_modules/.bin/webpack --config webpack.prod.js",
"serve": "webpack-dev-server --port 8080 --open --https --config webpack.dev.js",
"clean-branchs": "git branch | grep -v \"master\\|main\\|production\" | xargs git branch -D"
"clean-branchs": "git branch | grep -v \"master\\|main\\|production\" | xargs git branch -D",
"test" : "yarn jest"
},
"author": "",
"license": "ISC",
Expand All @@ -17,6 +18,7 @@
"@babel/plugin-proposal-class-properties": "^7.16.7",
"@babel/plugin-proposal-nullish-coalescing-operator": "^7.16.7",
"@babel/plugin-proposal-object-rest-spread": "^7.17.3",
"@babel/plugin-transform-runtime": "^7.24.3",
"@babel/preset-env": "^7.16.11",
"@babel/preset-flow": "^7.16.7",
"@babel/preset-react": "^7.16.7",
Expand Down Expand Up @@ -117,6 +119,59 @@
"xlsx": "^0.17.0"
},
"devDependencies": {
"css-minimizer-webpack-plugin": "^4.2.2"
"@testing-library/dom": "^10.1.0",
"@testing-library/jest-dom": "^6.4.2",
"@testing-library/react": "12.1.5",
"@testing-library/user-event": "^14.5.2",
"@types/react-dom": "16.9.24",
"babel-jest": "^29.7.0",
"css-minimizer-webpack-plugin": "^4.2.2",
"flush-promises": "^1.0.2",
"identity-obj-proxy": "^3.0.0",
"jest": "^29.7.0",
"jest-environment-jsdom": "^28.1.0",
"jest-transform-stub": "^2.0.0",
"redux-mock-store": "^1.5.4"
},
"jest": {
"collectCoverageFrom": [
"src/**/*.{js,jsx,mjs}"
],
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
"\\.(css|scss)$": "identity-obj-proxy"
},
"transformIgnorePatterns": [
"node_modules/react-rte"
],
"testMatch": [
"<rootDir>/src/**/__tests__/**/*.{js,jsx,mjs}",
"<rootDir>/src/**/?(*.)(spec|test).{js,jsx,mjs}"
],
"transform": {
"\\.[jt]sx?$": "babel-jest",
".+\\.(css|styl|less|sass|scss|png|jpg|ttf|woff|woff2)$": "jest-transform-stub"
},
"moduleDirectories": [
"node_modules",
"src"
],
"moduleFileExtensions": [
"web.js",
"js",
"json",
"web.jsx",
"jsx",
"node",
"mjs"
],
"globals": {
"window": {},
"console": {}
},
"testEnvironment": "jsdom",
"setupFilesAfterEnv": [
"<rootDir>/testSetupFile.js"
]
}
}
1 change: 1 addition & 0 deletions src/__mocks__/fileMock.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = {};
73 changes: 73 additions & 0 deletions src/actions/__tests__/actions.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/**
* @jest-environment jsdom
*/

import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk'
import flushPromises from 'flush-promises';
import * as SummitActions from '../../actions/summit-actions';
import * as methods from '../../utils/methods';
import { postRequest } from 'openstack-uicore-foundation/lib/utils/actions';

jest.mock('openstack-uicore-foundation/lib/utils/actions', () => {
return {
__esModule: true,
...jest.requireActual('openstack-uicore-foundation/lib/utils/actions'),
postRequest: jest.fn()
};
});

describe('summit actions', () => {
const middlewares = [thunk]
const mockStore = configureStore(middlewares);
const store = mockStore({});

beforeEach(() => { // Runs before each test in the suite
store.clearActions();
jest.spyOn(methods, "getAccessTokenSafely").mockReturnValue("TOKEN");
postRequest.mockImplementation((
requestActionCreator,
receiveActionCreator,
endpoint,
payload,
errorHandler = null,
requestActionPayload = {}
) => (params = {}) => (dispatch) => {
if(requestActionCreator && typeof requestActionCreator === 'function')
dispatch(requestActionCreator(requestActionPayload));

return new Promise((resolve) => {
if(typeof receiveActionCreator === 'function') {
dispatch(receiveActionCreator({response: {}}));
return resolve({response: {}});
}
dispatch(receiveActionCreator);
return resolve({response: {}});
});
})
});

afterEach(() => {
// restore the spy created with spyOn
jest.restoreAllMocks();
});

test('check AttachLogo expected actions', async () => {

const expectedActions = [
{"payload": undefined, "type": "START_LOADING"},
{"payload": {"response": {}}, "type": "DUMMY_ACTION"},
{"payload": {"logo": undefined}, "type": "SUMMIT_LOGO_ATTACHED"},
{"payload": undefined, "type": "STOP_LOADING"}
];

const f = new File([""], "filename", { type: 'text/html' });
store.dispatch(SummitActions.attachLogo({id: 1}, f, false ));
await flushPromises();

expect(store.getActions()).toEqual(expectedActions);
expect(postRequest).toBeCalledTimes(1);
expect(methods.getAccessTokenSafely).toBeCalledTimes(2);
});

});
4 changes: 2 additions & 2 deletions src/actions/summit-actions.js
Original file line number Diff line number Diff line change
Expand Up @@ -272,14 +272,14 @@ export const attachLogo = (entity, file, secondary = false) => async (dispatch,
}
}

const uploadLogo = (entity, file, secondary) => async (dispatch, getState) => {
const uploadLogo = (entity, file, secondary) => async (dispatch) => {
const accessToken = await getAccessTokenSafely();
const url = `${window.API_BASE_URL}/api/v1/summits/${entity.id}/logo${secondary ? '/secondary' : ''}`;
const params = {
access_token : accessToken
};

postRequest(
return postRequest(
null,
createAction(DUMMY_ACTION),
url,
Expand Down
110 changes: 110 additions & 0 deletions src/components/forms/__tests__/forms.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
/**
* @jest-environment jsdom
*/
import React from "react";
import {render, screen} from '@testing-library/react'
import '@testing-library/jest-dom'
import SummitForm from "../summit-form.js";

describe("form test", () => {
test("render summit form with Summit.name set to 'test summit'", async () => {
const currentSummit = {
id: 1,
name: 'test summit',
active: false,
allow_update_attendee_extra_questions: false,
attendees_count: 0,
available_on_api: false,
calendar_sync_desc: '',
calendar_sync_name: '',
dates_label: '',
end_date: 0,
event_types: [],
link: '',
locations: [],
logo: null,
secondary_logo: null,
page_url: '',
presentation_voters_count: 0,
presentation_votes_count: 0,
presentations_submitted_count: 0,
published_events_count: 0,
reassign_ticket_till_date: 0,
registration_begin_date: 0,
registration_end_date: 0,
registration_link: '',
registration_disclaimer_content: '',
registration_disclaimer_mandatory: false,
schedule_event_detail_url: '',
schedule_page_url: '',
schedule_start_date: 0,
secondary_registration_label: '',
secondary_registration_link: '',
speaker_announcement_email_accepted_alternate_count: 0,
speaker_announcement_email_accepted_count: 0,
speaker_announcement_email_accepted_rejected_count: 0,
speaker_announcement_email_alternate_count: 0,
speaker_announcement_email_alternate_rejected_count: 0,
speaker_announcement_email_rejected_count: 0,
speakers_count: 0,
start_date: 0,
start_showing_venues_date: 0,
slug: '',
supported_currencies: ['USD', 'EUR'],
ticket_types: [],
time_zone: {},
time_zone_id: '',
time_zone_label: '',
timestamp: 0,
tracks: [],
type_id: 0,
wifi_connections: [],
selection_plans: [],
meeting_booking_room_allowed_attributes: [],
meeting_room_booking_end_time: null,
meeting_room_booking_max_allowed: 0,
meeting_room_booking_slot_length: 0,
meeting_room_booking_start_time: null,
api_feed_type: '',
api_feed_url: '',
api_feed_key: '',
refund_policies: [],
access_level_types: null,
badge_types: null,
badge_features: null,
badge_view_types: null,
order_extra_questions: null,
order_only_extra_questions: null,
attendee_extra_questions: null,
attendee_main_extra_questions: null,
begin_allow_booking_date: 0,
end_allow_booking_date: 0,
external_summit_id: null,
external_registration_feed_type: '',
external_registration_feed_api_key: null,
virtual_site_url: null,
marketing_site_url: null,
mux_token_id: null,
mux_token_secret: null,
mux_allowed_domains: [],
help_users : [],
registration_send_qr_as_image_attachment_on_ticket_email : false,
registration_send_ticket_as_pdf_attachment_on_ticket_email : false,
registration_allow_automatic_reminder_emails : true,
registration_send_order_email_automatically: true,
qr_codes_enc_key: 'N/A',
speaker_confirmation_default_page_url: '',
marketing_site_oauth2_client_id:null,
marketing_site_oauth2_client_scopes: null,
available_lead_report_columns: [],
};

const timezones = ['UTC'];
const errors = {};

const { container } = render(<SummitForm entity={currentSummit} timezones={timezones} errors={errors}/>)
const element = container.querySelector("#name")
expect(element !== null).toBeTruthy();
expect(element.value === 'test summit').toBeTruthy();
});
});
3 changes: 3 additions & 0 deletions testSetupFile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { TextEncoder, TextDecoder } from 'util';
global.TextEncoder = TextEncoder;
global.TextDecoder = TextDecoder;
1 change: 1 addition & 0 deletions webpack.common.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ module.exports = {
buffer: require.resolve("buffer"),
fs: require.resolve('fs'),
process: require.resolve("process"),
vm: false,
}
},
module: {
Expand Down
Loading

0 comments on commit 3261dec

Please sign in to comment.