How to use actions.perform method in Appium

Best JavaScript code snippet using appium

ShowTransactions.test.js

Source:ShowTransactions.test.js Github

copy

Full Screen

1import React from 'react';2import { faHome } from '@fortawesome/fontawesome-free-solid';3import { Provider } from 'react-redux';4import ShowTransactionsContainer, { ShowTransactions } from '../ShowTransactions';5import { BackLink, Loader, RecentTransactions } from '../../../components';6import { mountWithIntl, shallowWithIntl } from '../../../services/intlTestHelper';7import { formatFloat } from '../../../services/formatter';8import configureMockStore from 'redux-mock-store';9import * as usersActions from '../../../action_performers/users';10import * as notificationActions from '../../../action_performers/notifications';11import * as txActions from '../../../action_performers/transactions';12import * as appActions from '../../../action_performers/app';13const context = {14 intl: {15 formatMessage: jest.fn()16 },17 router: {18 history: { push: jest.fn() }19 }20};21const mockStore = configureMockStore();22const store = mockStore({23 Users: {24 profile: {25 data: {26 user: {27 id: 128 }29 }30 }31 },32 Transactions: {33 recentTransactions: {34 data: {35 currentBalance: {36 date: 1523707200,37 balance: 40.438 },39 hasNextTransactions: 3,40 transactions: [41 {42 id: '1',43 date: 1523707200,44 producerName: 'Alice',45 energyAmount: 7.13,46 description: `Bought ${formatFloat(7.13)} kWh from "Alice"`,47 transactionAmount: 0.81,48 details: {49 status: 'success',50 hash: '9d98edfe27bb7f489fb1ced93d2b6e4093e5e40e5103356a602fecfc8d154743',51 price: 2.5,52 amount: 7.74,53 from: '254839457345934957394593459',54 url:55 'https://ropsten.etherscan.io/tx/0x25a23d106b2c4299a98e553d96570941556e53fe8808476ee0fceb5d72859540'56 }57 },58 {59 id: '2',60 date: 1523707200,61 producerName: 'Alice',62 energyAmount: 7.13,63 description: `Bought ${formatFloat(7.13)} kWh from "Alice"`,64 transactionAmount: 0.081,65 details: {66 status: 'success',67 hash: '9d98edfe27bb7f489fb1ced93d2b6e4093e5e40e5103356a602fecfc8d154743',68 price: 2.5,69 amount: 7.74,70 from: '254839457345934957394593459',71 url:72 'https://ropsten.etherscan.io/tx/0x25a23d106b2c4299a98e553d96570941556e53fe8808476ee0fceb5d72859540'73 }74 },75 {76 id: '3',77 date: 1523707200,78 producerName: 'Alice',79 energyAmount: 7.13,80 description: `Bought ${formatFloat(7.13)} kWh from "Alice"`,81 transactionAmount: 0.8,82 details: {83 status: 'success',84 hash: '9d98edfe27bb7f489fb1ced93d2b6e4093e5e40e5103356a602fecfc8d154743',85 price: 2.5,86 amount: 7.74,87 from: '254839457345934957394593459',88 url:89 'https://ropsten.etherscan.io/tx/0x25a23d106b2c4299a98e553d96570941556e53fe8808476ee0fceb5d72859540'90 }91 },92 {93 id: '4',94 date: 1523707200,95 producerName: 'Alice',96 energyAmount: 7.13,97 description: `Bought ${formatFloat(7.13)} kWh from "Alice"`,98 transactionAmount: 0.8,99 details: {100 status: 'success',101 hash: '9d98edfe27bb7f489fb1ced93d2b6e4093e5e40e5103356a602fecfc8d154743',102 price: 2.5,103 amount: 7.74,104 from: '254839457345934957394593459',105 url:106 'https://ropsten.etherscan.io/tx/0x25a23d106b2c4299a98e553d96570941556e53fe8808476ee0fceb5d72859540'107 }108 },109 {110 id: '5',111 date: 1523707200,112 producerName: 'Alice',113 energyAmount: 7.13,114 description: `Bought ${formatFloat(7.13)} kWh from "Alice"`,115 transactionAmount: 0.8,116 details: {117 status: 'success',118 hash: '9d98edfe27bb7f489fb1ced93d2b6e4093e5e40e5103356a602fecfc8d154743',119 price: 2.5,120 amount: 7.74,121 from: '254839457345934957394593459',122 url:123 'https://ropsten.etherscan.io/tx/0x25a23d106b2c4299a98e553d96570941556e53fe8808476ee0fceb5d72859540'124 }125 },126 {127 id: '6',128 date: 1523707200,129 producerName: 'Alice',130 energyAmount: 7.13,131 description: `Bought ${formatFloat(7.13)} kWh from "Alice"`,132 transactionAmount: 0.8,133 details: {134 status: 'success',135 hash: '9d98edfe27bb7f489fb1ced93d2b6e4093e5e40e5103356a602fecfc8d154743',136 price: 2.5,137 amount: 7.74,138 from: '254839457345934957394593459',139 url:140 'https://ropsten.etherscan.io/tx/0x25a23d106b2c4299a98e553d96570941556e53fe8808476ee0fceb5d72859540'141 }142 },143 {144 id: '7',145 date: 1523707200,146 producerName: 'Alice',147 energyAmount: 7.13,148 description: `Bought ${formatFloat(7.13)} kWh from "Alice"`,149 transactionAmount: 0.8,150 details: {151 status: 'success',152 hash: '9d98edfe27bb7f489fb1ced93d2b6e4093e5e40e5103356a602fecfc8d154743',153 price: 2.5,154 amount: 7.74,155 from: '254839457345934957394593459',156 url:157 'https://ropsten.etherscan.io/tx/0x25a23d106b2c4299a98e553d96570941556e53fe8808476ee0fceb5d72859540'158 }159 }160 ]161 },162 loading: false,163 error: null164 }165 },166 App: {167 localization: {168 data: {169 locale: 'en'170 }171 }172 }173});174const props = {175 recentTransactions: {176 currentBalance: {177 date: 1523707200,178 balance: 40.4179 },180 hasNextTransactions: 3,181 transactions: [182 {183 id: '1',184 date: 1523707200,185 producerName: 'Alice',186 energyAmount: 7.13,187 description: `Bought ${formatFloat(7.13)} kWh from "Alice"`,188 transactionAmount: 0.81,189 details: {190 status: 'success',191 hash: '9d98edfe27bb7f489fb1ced93d2b6e4093e5e40e5103356a602fecfc8d154743',192 price: 2.5,193 amount: 7.74,194 from: '254839457345934957394593459',195 url:196 'https://ropsten.etherscan.io/tx/0x25a23d106b2c4299a98e553d96570941556e53fe8808476ee0fceb5d72859540'197 }198 },199 {200 id: '2',201 date: 1523707200,202 producerName: 'Alice',203 energyAmount: 7.13,204 description: `Bought ${formatFloat(7.13)} kWh from "Alice"`,205 transactionAmount: 0.081,206 details: {207 status: 'success',208 hash: '9d98edfe27bb7f489fb1ced93d2b6e4093e5e40e5103356a602fecfc8d154743',209 price: 2.5,210 amount: 7.74,211 from: '254839457345934957394593459',212 url:213 'https://ropsten.etherscan.io/tx/0x25a23d106b2c4299a98e553d96570941556e53fe8808476ee0fceb5d72859540'214 }215 },216 {217 id: '3',218 date: 1523707200,219 producerName: 'Alice',220 energyAmount: 7.13,221 description: `Bought ${formatFloat(7.13)} kWh from "Alice"`,222 transactionAmount: 0.8,223 details: {224 status: 'success',225 hash: '9d98edfe27bb7f489fb1ced93d2b6e4093e5e40e5103356a602fecfc8d154743',226 price: 2.5,227 amount: 7.74,228 from: '254839457345934957394593459',229 url:230 'https://ropsten.etherscan.io/tx/0x25a23d106b2c4299a98e553d96570941556e53fe8808476ee0fceb5d72859540'231 }232 },233 {234 id: '4',235 date: 1523707200,236 producerName: 'Alice',237 energyAmount: 7.13,238 description: `Bought ${formatFloat(7.13)} kWh from "Alice"`,239 transactionAmount: 0.8,240 details: {241 status: 'success',242 hash: '9d98edfe27bb7f489fb1ced93d2b6e4093e5e40e5103356a602fecfc8d154743',243 price: 2.5,244 amount: 7.74,245 from: '254839457345934957394593459',246 url:247 'https://ropsten.etherscan.io/tx/0x25a23d106b2c4299a98e553d96570941556e53fe8808476ee0fceb5d72859540'248 }249 },250 {251 id: '5',252 date: 1523707200,253 producerName: 'Alice',254 energyAmount: 7.13,255 description: `Bought ${formatFloat(7.13)} kWh from "Alice"`,256 transactionAmount: 0.8,257 details: {258 status: 'success',259 hash: '9d98edfe27bb7f489fb1ced93d2b6e4093e5e40e5103356a602fecfc8d154743',260 price: 2.5,261 amount: 7.74,262 from: '254839457345934957394593459',263 url:264 'https://ropsten.etherscan.io/tx/0x25a23d106b2c4299a98e553d96570941556e53fe8808476ee0fceb5d72859540'265 }266 },267 {268 id: '6',269 date: 1523707200,270 producerName: 'Alice',271 energyAmount: 7.13,272 description: `Bought ${formatFloat(7.13)} kWh from "Alice"`,273 transactionAmount: 0.8,274 details: {275 status: 'success',276 hash: '9d98edfe27bb7f489fb1ced93d2b6e4093e5e40e5103356a602fecfc8d154743',277 price: 2.5,278 amount: 7.74,279 from: '254839457345934957394593459',280 url:281 'https://ropsten.etherscan.io/tx/0x25a23d106b2c4299a98e553d96570941556e53fe8808476ee0fceb5d72859540'282 }283 },284 {285 id: '7',286 date: 1523707200,287 producerName: 'Alice',288 energyAmount: 7.13,289 description: `Bought ${formatFloat(7.13)} kWh from "Alice"`,290 transactionAmount: 0.8,291 details: {292 status: 'success',293 hash: '9d98edfe27bb7f489fb1ced93d2b6e4093e5e40e5103356a602fecfc8d154743',294 price: 2.5,295 amount: 7.74,296 from: '254839457345934957394593459',297 url:298 'https://ropsten.etherscan.io/tx/0x25a23d106b2c4299a98e553d96570941556e53fe8808476ee0fceb5d72859540'299 }300 }301 ]302 },303 locale: 'en',304 user: { id: 'testId' },305 loading: false,306 error: null307};308function renderContainer() {309 return mountWithIntl(310 <Provider store={store}>311 <ShowTransactionsContainer context={context} />312 </Provider>313 );314}315function renderComponent() {316 return shallowWithIntl(<ShowTransactions {...props} context={context} />);317}318describe('<ShowTransactions /> Component', () => {319 jest.useFakeTimers();320 const mainContainerMock = document.createElement('div');321 beforeEach(() => {322 context.router.history.push = jest.fn();323 context.intl.formatMessage = jest.fn();324 usersActions.performGetUserData = jest.fn();325 txActions.performGetRecentTransactions = jest.fn();326 notificationActions.performPushNotification = jest.fn();327 appActions.performSetupLoaderVisibility = jest.fn();328 appActions.performSetupBreadcrumbs = jest.fn();329 jest.spyOn(document, 'getElementById').mockReturnValue(mainContainerMock);330 jest.spyOn(mainContainerMock, 'addEventListener');331 jest.spyOn(mainContainerMock, 'removeEventListener');332 });333 it(`should contains following controls:334 - 1 <RecentTransactions /> component;335 - 2 <section> elements;336 - 1 <h1> element;`, () => {337 const component = renderContainer();338 expect(component.find('section.show-transaction-page')).toHaveLength(1);339 expect(component.find('section')).toHaveLength(2);340 expect(component.find(RecentTransactions)).toHaveLength(1);341 expect(component.find(BackLink)).toHaveLength(1);342 expect(component.find('h1')).toHaveLength(1);343 });344 it('should handler scroll event', () => {345 const component = renderComponent();346 const handleScrollMock = component.instance().scrollHandler;347 expect(mainContainerMock.addEventListener).toHaveBeenCalledWith('scroll', component.instance().scrollHandler);348 component.unmount();349 expect(mainContainerMock.removeEventListener).toHaveBeenCalledWith('scroll', handleScrollMock);350 });351 it('should provide possibility back to overview page through header', () => {352 const event = { preventDefault: jest.fn() };353 const component = renderComponent();354 component.setContext(context);355 const backLink = component.find(BackLink).at(0);356 backLink.simulate('click', event);357 expect(context.router.history.push).toHaveBeenCalledWith('/');358 expect(event.preventDefault).toHaveBeenCalled();359 });360 it('should call prepare common function', () => {361 const component = renderContainer();362 const table = component.find(RecentTransactions).at(0);363 const tableProps = table.props();364 delete tableProps.onButtonClick;365 expect(tableProps).toEqual({366 currentBalance: { ...props.recentTransactions.currentBalance },367 labels: {368 buyCoinsButton: 'Buy Coins',369 header: 'Show Transactions',370 recentTransactionsDetailsAmount: 'Amount',371 recentTransactionsDetailsFrom: 'From',372 recentTransactionsDetailsHash: 'Blockchain Transaction',373 recentTransactionsDetailsPrice: 'Price per kWh',374 recentTransactionsDetailsStatus: 'Status',375 recentTransactionsHeaderAmount: 'Amount',376 recentTransactionsHeaderDate: 'Date',377 recentTransactionsHeaderTransaction: 'Transaction',378 recentTransactionsMonthlyBalance: 'Monthly Balance',379 recentTransactionsMore: 'More',380 recentTransactionsTitle: 'Most Recent Transactions',381 recentTransactionsDescriptionBought: 'Bought',382 recentTransactionsDescriptionFrom: 'from',383 sellCoinsButton: 'Sell Coins',384 loadingErrorMessage:385 "Can't load transactions data from PowerChain web server. Please contact administrator to resolve the error."386 },387 loading: false,388 pagination: true,389 transactions: [390 ...props.recentTransactions.transactions.map(tx => ({391 ...tx,392 details: { ...tx.details, status: 'Success' }393 }))394 ]395 });396 });397 it('should returns correct props map', () => {398 const stateDummy = {399 Transactions: {400 recentTransactions: {401 data: {402 numberOfTransactions: 20,403 transactions: ['tx_test']404 },405 error: null,406 loading: 'tx_loading'407 }408 },409 Users: {410 profile: {411 data: { user: 'user_data' },412 error: 'test_error',413 loading: 'test_loading'414 }415 },416 App: {417 localization: {418 data: {419 locale: 'en'420 }421 }422 }423 };424 const props = ShowTransactions.mapStateToProps(stateDummy);425 expect(props).toEqual({426 locale: 'en',427 recentTransactions: {428 numberOfTransactions: 20,429 transactions: ['tx_test']430 },431 hasNextTransactions: true,432 transactionsLoading: 'tx_loading',433 user: 'user_data',434 error: 'test_error',435 loading: 'test_loading'436 });437 });438 it('should perform related actions on did mount step', () => {439 renderContainer();440 expect(appActions.performSetupBreadcrumbs.mock.calls.length).toEqual(2);441 const [, [bArg1]] = appActions.performSetupBreadcrumbs.mock.calls;442 expect(bArg1).toEqual([443 { icon: faHome, id: '', label: 'Overview', path: '/' },444 { id: 'show_transactions', label: 'Show Transactions', path: '/show_transactions' }445 ]);446 expect(usersActions.performGetUserData.mock.calls.length).toEqual(1);447 const component = renderComponent();448 expect(usersActions.performGetUserData.mock.calls.length).toEqual(2);449 expect(txActions.performGetRecentTransactions.mock.calls.length).toEqual(0);450 component.setProps({ user: { id: 10 } });451 expect(txActions.performGetRecentTransactions.mock.calls.length).toEqual(1);452 const [[userId]] = txActions.performGetRecentTransactions.mock.calls;453 expect(userId).toEqual(10);454 component.setProps({ error: { message: 'Error Message' } });455 expect(notificationActions.performPushNotification.mock.calls.length).toEqual(1);456 const [[error]] = notificationActions.performPushNotification.mock.calls;457 expect(error).toEqual({458 message:459 "Can't load transactions data from PowerChain web server. Please contact administrator to resolve the error.",460 type: 'error'461 });462 });463 it('should calls performSetupLoaderVisibility when receive new loading property', () => {464 const showTransactions = renderComponent();465 showTransactions.setProps({ loading: true });466 expect(appActions.performSetupLoaderVisibility).toHaveBeenCalledWith(expect.anything(), true);467 showTransactions.setProps({ loading: false });468 expect(appActions.performSetupLoaderVisibility).toHaveBeenCalledWith(expect.anything(), false);469 expect(appActions.performSetupLoaderVisibility).toHaveBeenCalledTimes(2);470 });471 it('should call scroll handler of the container', () => {472 const showTransactions = renderComponent();473 const dummyEvent = {474 target: {475 scrollTop: 10,476 clientHeight: 10,477 scrollHeight: 10478 }479 };480 showTransactions.setProps({481 hasNextTransactions: true,482 transactionsLoading: false483 });484 showTransactions.instance().scrollHandler(dummyEvent);485 jest.runAllTimers();486 expect(showTransactions.state('page')).toBe(1);487 });488 it('should setup translated breadcrumbs when locale changed', () => {489 const showTransactions = renderComponent();490 expect(appActions.performSetupBreadcrumbs).toHaveBeenCalledTimes(2);491 showTransactions.setProps({492 locale: 'de'493 });494 expect(appActions.performSetupBreadcrumbs).toHaveBeenCalledTimes(3);495 });...

Full Screen

Full Screen

App.test.js

Source:App.test.js Github

copy

Full Screen

1import React from 'react';2import faHome from '@fortawesome/fontawesome-free-solid/faHome';3import faBook from '@fortawesome/fontawesome-free-solid/faBook';4import faSuitcase from '@fortawesome/fontawesome-free-solid/faSuitcase';5import faCalculator from '@fortawesome/fontawesome-free-solid/faCalculator';6import faUser from '@fortawesome/fontawesome-free-solid/faUser';7import faShoppingCart from '@fortawesome/fontawesome-free-solid/faShoppingCart';8import { App } from '../App';9import { Header, MenuSideBar, Footer, ContractModal } from '../../../components';10import * as usersActions from '../../../action_performers/users';11import * as appActions from '../../../action_performers/app';12import * as contractsActions from '../../../action_performers/contracts';13import * as notificationsActions from '../../../action_performers/notifications';14import { shallowWithIntl } from '../../../services/intlTestHelper';15const context = {16 intl: { formatMessage: jest.fn() },17 router: {18 history: { push: jest.fn() }19 },20 user: { contract: {} }21};22function renderComponent(props = { user: { contract: {} } }) {23 return shallowWithIntl(<App {...props} />);24}25describe('Main <App /> Component', () => {26 beforeEach(() => {27 context.router.history.push = jest.fn();28 context.intl.formatMessage = jest.fn();29 usersActions.performLogout = jest.fn();30 usersActions.performGetUserData = jest.fn();31 contractsActions.performGetSessionContract = jest.fn();32 contractsActions.performGetContracts = jest.fn();33 contractsActions.performSetSessionContract = jest.fn();34 appActions.performSetupLocale = jest.fn();35 appActions.performSetupLoaderVisibility = jest.fn();36 notificationsActions.performPushNotification = jest.fn();37 });38 afterEach(() => {39 appActions.performSetupLocale.mockClear();40 });41 it(`should contain following controls:42 - <div> with class "app";43 - <Header> component";44 - <Footer> component";45 - <MenuSideBar> component"46 - <ContractModal> component";`, () => {47 const component = renderComponent(context);48 const text = component.debug();49 expect(text.includes('div className="app"')).toEqual(true);50 expect(component.find(Header)).toHaveLength(1);51 expect(component.find(Footer)).toHaveLength(1);52 expect(component.find(MenuSideBar)).toHaveLength(1);53 expect(component.find(ContractModal)).toHaveLength(1);54 });55 it('should return correct props', () => {56 const stateMock = {57 Contracts: {58 contracts: {59 loading: false,60 error: null,61 data: [{ id: 'testContractId' }]62 },63 sessionContract: {64 loading: false,65 error: null,66 data: { id: 'testContractId' }67 },68 updatedSessionContract: {69 loading: false,70 error: 'Update Error',71 data: { id: 'testContractId' }72 }73 },74 Users: {75 profile: {76 data: {77 user: { id: 1, contract: {} }78 }79 },80 login: {},81 logout: { loading: false }82 },83 App: {84 breadCrumbs: {85 data: []86 },87 localization: {88 data: {89 locale: 'en',90 aboutUs: [],91 faq: []92 },93 loading: {94 aboutUs: false,95 faq: false96 }97 }98 }99 };100 const props = App.mapStateToProps(stateMock);101 expect(props).toEqual({102 breadCrumbs: [],103 contracts: [{ id: 'testContractId' }],104 errorContracts: null,105 errorSetContract: 'Update Error',106 loading: false,107 locale: 'en',108 loggingOut: false,109 sessionContract: { id: 'testContractId' },110 updatedSessionContract: { id: 'testContractId' },111 user: { id: 1, contract: {} }112 });113 });114 it('should setup correct callbacks and handle related events for Header', () => {115 const component = renderComponent({116 ...context,117 contracts: [{ id: '100020' }],118 sessionContract: { id: '100020' }119 });120 component.setContext(context);121 const header = component.find(Header).at(0);122 const confirm = component.find('Confirm');123 expect(component.state().isLogoutConfirmVisible).toEqual(false);124 header.props().onLogoutClick();125 expect(component.state().isLogoutConfirmVisible).toEqual(true);126 confirm.props().onConfirm();127 component.setProps({ loggingOut: true });128 component.setProps({ loggingOut: false });129 expect(context.router.history.push.mock.calls.length).toEqual(1);130 expect(usersActions.performLogout.mock.calls.length).toEqual(1);131 const [[route]] = context.router.history.push.mock.calls;132 expect(route).toEqual('/login');133 });134 it('should correctly handle cases when working contracts are absent', () => {135 const component = renderComponent({ ...context, contracts: [], sessionContract: { id: '100020' } });136 component.setContext(context);137 expect(contractsActions.performSetSessionContract).toHaveBeenCalledTimes(0);138 expect(component.find('ContractModal').props().show).toEqual(true);139 expect(component.find('ContractModal').props().labels).toEqual({140 contractMessage: 'To continue, please select a contract.',141 noContractMessage:142 'At present, no contract data can be displayed. Please contact the administrator or try again later.',143 selectLabel: 'Select contract'144 });145 component.setProps({146 contracts: [{ id: '100020' }],147 sessionContract: null,148 user: { id: 'testId', contract: {} }149 });150 expect(component.find('ContractModal').props().show).toEqual(true);151 component152 .find('ContractModal')153 .props()154 .onSelect({ value: '100020' });155 expect(contractsActions.performSetSessionContract).toHaveBeenCalledWith('testId', '100020');156 component.setProps({ contracts: [{ id: '100020' }], sessionContract: { id: '100020' } });157 expect(component.find('ContractModal').props().show).toEqual(false);158 });159 it('should correctly handle logout cases when working contracts are absent', () => {160 const component = renderComponent({ ...context, contracts: [], sessionContract: { id: '100020' } });161 component.setContext(context);162 expect(component.state().isLogoutConfirmVisible).toEqual(false);163 component164 .find(Header)165 .at(0)166 .props()167 .onLogoutClick();168 expect(component.state().isLogoutConfirmVisible).toEqual(false);169 component.setProps({ loggingOut: true });170 component.setProps({ loggingOut: false });171 expect(context.router.history.push.mock.calls.length).toEqual(1);172 expect(usersActions.performLogout.mock.calls.length).toEqual(1);173 const [[route]] = context.router.history.push.mock.calls;174 expect(route).toEqual('/login');175 });176 it('should correctly handle logout cases when session contract is absent', () => {177 const component = renderComponent({ ...context, contracts: [{ id: '100020' }], sessionContract: null });178 component.setContext(context);179 expect(component.state().isLogoutConfirmVisible).toEqual(false);180 component181 .find(Header)182 .at(0)183 .props()184 .onLogoutClick();185 expect(component.state().isLogoutConfirmVisible).toEqual(false);186 component.setProps({ loggingOut: true });187 component.setProps({ loggingOut: false });188 expect(context.router.history.push.mock.calls.length).toEqual(1);189 expect(usersActions.performLogout.mock.calls.length).toEqual(1);190 const [[route]] = context.router.history.push.mock.calls;191 expect(route).toEqual('/login');192 });193 it(`should correctly show 'No contracts message' on mobile view when working contracts are absent`, () => {194 const componentWithContracts = renderComponent({ ...context, contracts: [{ id: '100020' }] });195 componentWithContracts.setContext(context);196 expect(componentWithContracts.find('.config-contract-select')).toHaveLength(2);197 expect(componentWithContracts.find('.contract-config-select-no-contracts-alert')).toHaveLength(0);198 const componentWithoutContracts = renderComponent({ ...context, contracts: [] });199 componentWithoutContracts.setContext(context);200 expect(componentWithoutContracts.find('.config-contract-select')).toHaveLength(1);201 expect(componentWithoutContracts.find('.contract-config-select-no-contracts-alert')).toHaveLength(1);202 expect(componentWithoutContracts.find('.contract-config-select-no-contracts-alert').text()).toEqual(203 'No contracts'204 );205 });206 it('should setup correct callbacks and handle related events for MenuSideBar', () => {207 const component = renderComponent(context);208 component.setContext(context);209 const menu = component.find(MenuSideBar).at(0);210 menu.props().onSelect('/item1');211 expect(context.router.history.push.mock.calls.length).toEqual(1);212 const [[route]] = context.router.history.push.mock.calls;213 expect(route).toEqual('/item1');214 expect(menu.props().items).toEqual([215 { active: true, icon: faHome, id: '', label: 'Overview', path: '/', subItemActive: false },216 { active: false, icon: faBook, id: 'documents', label: 'My Documents', path: '/documents' },217 {218 active: false,219 icon: faCalculator,220 id: 'submit_meter',221 label: 'Submit Meter Readings',222 path: '/submit_meter'223 },224 {225 active: false,226 subItemActive: false,227 icon: faShoppingCart,228 id: 'buy_energy',229 label: 'Buy energy',230 path: '/buy_energy',231 disabled: true232 },233 {234 active: false,235 icon: faSuitcase,236 id: 'direct_trading',237 label: 'Direct Trading',238 path: '/direct_trading',239 disabled: true240 },241 { active: false, icon: faUser, id: 'profile', label: 'Profile', path: '/profile' }242 ]);243 });244 it('should setup correct callbacks and handle related events for Footer anchors', () => {245 const component = renderComponent(context);246 component.setContext(context);247 const footer = component.find(Footer).at(0);248 footer.props().onSelect('/item1');249 expect(context.router.history.push.mock.calls.length).toEqual(1);250 const [[route]] = context.router.history.push.mock.calls;251 expect(route).toEqual('/item1');252 expect(footer.props().navItems).toEqual([253 { active: false, href: '/about', label: 'About Us' },254 { active: false, href: '/termsandconditions', label: 'Terms & Conditions' },255 { active: false, href: '/faq', label: 'FAQ' }256 ]);257 });258 it('should not perform logout if user click cancel', () => {259 const component = renderComponent({260 ...context,261 contracts: [{ id: '100020' }],262 sessionContract: { id: '100020' }263 });264 component.setContext(context);265 const header = component.find(Header).at(0);266 const confirm = component.find('Confirm');267 expect(component.state().isLogoutConfirmVisible).toEqual(false);268 header.props().onLogoutClick();269 expect(component.state().isLogoutConfirmVisible).toEqual(true);270 confirm.props().onCancel();271 expect(component.state().isLogoutConfirmVisible).toEqual(false);272 expect(context.router.history.push).not.toHaveBeenCalled();273 expect(usersActions.performLogout).not.toHaveBeenCalled();274 });275 it('should navigate to necessary route', () => {276 const component = renderComponent(context);277 component.setContext(context);278 const header = component.find(Header).at(0);279 header.props().onBreadCrumbsClick('/test');280 expect(context.router.history.push).toHaveBeenCalledWith('/test');281 });282 it('should call performSetupLocale when locale was changed', () => {283 const app = renderComponent();284 app285 .find('Header')286 .props()287 .onLocaleChange('de');288 expect(appActions.performSetupLocale).toHaveBeenCalledWith('de');289 });290 it('should provide possibility to de-emphasize content area and revert this option', () => {291 const component = renderComponent();292 expect(component.update().find('.covered-by-menu')).toHaveLength(0);293 expect(component.update().find('.covered-by-config-sidebar')).toHaveLength(0);294 expect(component.find('.content--de-emphasized')).toHaveLength(0);295 component296 .find(Header)297 .at(0)298 .props()299 .onToggleMenuBar();300 expect(component.update().find('.covered-by-menu')).toHaveLength(1);301 expect(component.update().find('.content--de-emphasized')).toHaveLength(1);302 component303 .find('.content')304 .at(0)305 .props()306 .onClick({307 target: {308 classList: {309 contains: className => 'content--de-emphasized' === className310 }311 }312 });313 expect(component.update().find('.covered-by-menu')).toHaveLength(0);314 expect(component.update().find('.content--de-emphasized')).toHaveLength(0);315 component316 .find(Header)317 .at(0)318 .props()319 .onToggleConfigSideBar();320 expect(component.update().find('.covered-by-config-sidebar')).toHaveLength(1);321 expect(component.update().find('.content--de-emphasized')).toHaveLength(1);322 component323 .find('.content')324 .at(0)325 .props()326 .onClick({327 target: {328 classList: {329 contains: className => 'content--de-emphasized' === className330 }331 }332 });333 expect(component.update().find('.covered-by-config-sidebar')).toHaveLength(0);334 expect(component.update().find('.content--de-emphasized')).toHaveLength(0);335 });336 it('should call performSetupLoaderVisibility when receive new loading property', () => {337 const app = renderComponent();338 app.setProps({ loading: true });339 expect(appActions.performSetupLoaderVisibility).toHaveBeenCalledWith(expect.anything(), true);340 app.setProps({ loading: false });341 expect(appActions.performSetupLoaderVisibility).toHaveBeenCalledWith(expect.anything(), true);342 expect(appActions.performSetupLoaderVisibility).toHaveBeenCalledTimes(2);343 });344 it('should call contracts action performers when receive new user data', () => {345 const app = renderComponent();346 expect(usersActions.performGetUserData).toHaveBeenCalledTimes(1);347 expect(contractsActions.performGetSessionContract).toHaveBeenCalledTimes(0);348 expect(contractsActions.performGetContracts).toHaveBeenCalledTimes(0);349 expect(contractsActions.performSetSessionContract).toHaveBeenCalledTimes(0);350 app.setProps({ user: { id: 'testId', contract: {} } });351 expect(contractsActions.performGetSessionContract).toHaveBeenCalledWith('testId');352 expect(contractsActions.performGetContracts).toHaveBeenCalledWith('testId');353 expect(contractsActions.performSetSessionContract).toHaveBeenCalledTimes(0);354 app.setProps({ contracts: [{ id: '0123' }, { id: '0124' }], sessionContract: { id: '0123' } });355 expect(app.find('Header').props().selectedContractId).toEqual('0123');356 expect(app.find('Header').props().contracts).toEqual([{ id: '0123' }, { id: '0124' }]);357 app358 .find('Header')359 .props()360 .onContractChange('0123');361 expect(contractsActions.performSetSessionContract).toHaveBeenCalledTimes(0);362 app363 .find('Header')364 .props()365 .onContractChange('0124');366 expect(contractsActions.performSetSessionContract).toHaveBeenCalledWith('testId', '0124');367 expect(contractsActions.performGetSessionContract).toHaveBeenCalledTimes(1);368 app.setProps({ updatedSessionContract: { id: '0124' } });369 expect(usersActions.performGetUserData).toHaveBeenCalledTimes(2);370 app.setProps({ user: { id: 'testId', contract: { statusCode: 5000 } } });371 expect(contractsActions.performGetSessionContract).toHaveBeenCalledTimes(2);372 });373 it('should correctly handle errors using notifications', () => {374 const app = renderComponent();375 expect(notificationsActions.performPushNotification).toHaveBeenCalledTimes(0);376 app.setProps({ errorContracts: { message: 'Internal Server Error' } });377 expect(notificationsActions.performPushNotification).toHaveBeenCalledWith({378 message:379 'An error occurred while getting contracts data. Please try to refresh page later or contact administrator.',380 type: 'error'381 });382 app.setProps({ errorSetContract: { message: 'Internal Server Error' } });383 expect(notificationsActions.performPushNotification).toHaveBeenCalledTimes(2);384 expect(notificationsActions.performPushNotification).toHaveBeenCalledWith({385 message:386 'An error occurred while getting contracts data. Please try to refresh page later or contact administrator.',387 type: 'error'388 });389 });390 it('should navigate to overview page', () => {391 const app = renderComponent(context);392 app.setContext(context);393 app394 .find('Header')395 .props()396 .onLogoClick();397 expect(context.router.history.push).toHaveBeenCalledWith('/');398 });399 it('should set class to main element for fix height when is meter reading page', () => {400 Object.defineProperty(window.location, 'pathname', {401 writable: true,402 value: '/submit_meter'403 });404 const app = renderComponent(context);405 app.setContext(context);406 expect(app.find('#main-container').hasClass('main-container--fixed-height')).toBeTruthy();407 });...

Full Screen

Full Screen

Producer.test.js

Source:Producer.test.js Github

copy

Full Screen

1import React from 'react';2import { Provider } from 'react-redux';3import faShoppingCart from '@fortawesome/fontawesome-free-solid/faShoppingCart';4import ProducerContainer, { Producer } from '../Producer';5import { ProducerInfo, Button, HelpIcon } from '../../../components';6import { mountWithIntl, shallowWithIntl } from '../../../services/intlTestHelper';7import configureMockStore from 'redux-mock-store';8import * as producersActions from '../../../action_performers/producers';9import * as appActions from '../../../action_performers/app';10import * as notificationActions from '../../../action_performers/notifications';11import * as usersActions from '../../../action_performers/users';12import { CONTRACT_STATUSES } from '../../../constants';13const mockStore = configureMockStore();14const store = mockStore({15 Users: {16 profile: {17 data: {18 user: {19 id: 0,20 firstName: 'string',21 lastName: 'string',22 email: 'string',23 currentProducerId: 1,24 lastBillAvailable: true,25 lastBillAmount: '35.24',26 lastBillDate: 'December;',27 userStatus: 'string',28 workingPrice: 2.3,29 contract: {30 statusCode: CONTRACT_STATUSES.active,31 statusCodeTitle: 'In Supply'32 }33 }34 }35 }36 },37 Producers: {38 producer: {39 data: {40 name: 'Producer',41 price: 2.4,42 annualProduction: 3000,43 purchased: 1300,44 capacity: 8,45 dates: 'Sep 12 - Feb 22',46 tradingStrategy: false,47 id: 1,48 complete: false,49 plantType: 'solar',50 picture: 'https://pbs.twimg.com/profile_images/929933611754708992/ioSgz49P_400x400.jpg',51 location: 'Lippendorf, Neukieritzsch',52 ethereumAddress: '123',53 description: 'desc',54 status: 'active'55 },56 loading: false,57 error: null58 },59 selectedProducer: {60 data: {},61 loading: false,62 error: null63 }64 },65 App: {66 localization: {67 data: {68 locale: 'en'69 }70 }71 }72});73const context = {74 intl: {75 formatMessage: jest.fn()76 },77 router: {78 history: { push: jest.fn() }79 }80};81const commonProps = {82 match: { params: { producerId: '1' } }83};84const props = {85 ...Producer.defaultProps,86 producer: {87 id: 1,88 name: 'test',89 status: 'active'90 },91 user: { id: 1, contract: { statusCode: CONTRACT_STATUSES.active } },92 selectedProducer: {},93 error: null94};95function renderContainer() {96 return mountWithIntl(97 <Provider store={store}>98 <ProducerContainer {...commonProps} context={context} />99 </Provider>100 );101}102function renderComponent() {103 return shallowWithIntl(<Producer {...commonProps} {...props} context={context} />);104}105describe('<Producer /> Component', () => {106 beforeEach(() => {107 context.router.history.push = jest.fn();108 context.intl.formatMessage = jest.fn();109 context.intl.formatMessage.mockReturnValue('test');110 producersActions.performGetProducer = jest.fn();111 producersActions.performSelectProducer = jest.fn();112 appActions.performSetupBreadcrumbs = jest.fn();113 appActions.performSetupLoaderVisibility = jest.fn();114 usersActions.performGetUserData = jest.fn();115 notificationActions.performPushNotification = jest.fn();116 });117 it(`should contains following controls:118 - <section> with class "producer-page";119 - 1 <h1>;120 - 2 <Button> component";121 - 1 <ProducerInfo> component";`, () => {122 const component = renderContainer();123 expect(component.find('section.producer-page')).toHaveLength(1);124 expect(component.find('h1')).toHaveLength(1);125 expect(component.find(ProducerInfo)).toHaveLength(1);126 expect(component.find(Button)).toHaveLength(2);127 expect(component.find(HelpIcon)).toHaveLength(0);128 expect(component.find('strong[aria-label="Producer Status"]')).toHaveLength(0);129 });130 it('should disable "Select Producer" button if producer has "sold out" status', () => {131 const component = renderComponent();132 component.setProps({133 producer: {134 id: 1,135 name: 'test',136 status: 'sold out'137 }138 });139 expect(component.find(HelpIcon)).toHaveLength(1);140 expect(component.find('strong[aria-label="Producer Status"]')).toHaveLength(1);141 expect(142 component143 .find(Button)144 .at(1)145 .props('disabled')146 ).toBeTruthy();147 });148 it('should call prepare common function', () => {149 const component = renderContainer();150 const info = component.find(ProducerInfo).at(0);151 expect(info.props()).toEqual({152 description: 'desc',153 details: {154 annualProduction: 3000,155 capacity: 8,156 energyType: 'Solar',157 location: 'Lippendorf, Neukieritzsch',158 name: 'Producer',159 price: 2.4,160 purchased: 1300,161 selectedSince: 'Sep 12 - Feb 22',162 ethereumAddress: '123',163 marketPrice: 2.3,164 status: 'active'165 },166 labels: {167 annualProduction: 'Annual Production',168 capacity: 'Peak Capacity',169 energyType: 'Type of energy',170 location: 'Location',171 name: 'Name',172 price: 'Price',173 marketPrice: 'vs. market price of',174 purchased: 'Energy purchased',175 selectedSince: 'Selected since',176 ethereumAddress: 'Ethereum Address'177 },178 picture: 'https://pbs.twimg.com/profile_images/929933611754708992/ioSgz49P_400x400.jpg'179 });180 });181 it('should returns correct props map', () => {182 const stateDummy = {183 Producers: {184 producer: {185 data: 'test_producer_data',186 error: 'test_producer_error',187 loading: false188 },189 selectedProducer: {190 data: 'test_selected_data',191 error: 'test_error',192 loading: 'test_loading'193 }194 },195 Users: {196 profile: {197 data: { user: 'user_data' },198 error: null,199 loading: false200 }201 },202 App: {203 localization: {204 data: {205 locale: 'en'206 }207 }208 }209 };210 const props = Producer.mapStateToProps(stateDummy);211 expect(props).toEqual({212 error: 'test_producer_error',213 errorSelect: 'test_error',214 loading: 'test_loading',215 locale: 'en',216 producer: 'test_producer_data',217 user: 'user_data',218 selectedProducer: 'test_selected_data'219 });220 });221 it('should perform related actions on lifecycle step', () => {222 renderContainer();223 expect(usersActions.performGetUserData.mock.calls.length).toEqual(1);224 expect(producersActions.performGetProducer.mock.calls.length).toEqual(1);225 const [[arg1]] = producersActions.performGetProducer.mock.calls;226 expect(arg1).toEqual('1');227 expect(appActions.performSetupBreadcrumbs.mock.calls.length).toEqual(2);228 const [, [bArg1]] = appActions.performSetupBreadcrumbs.mock.calls;229 expect(bArg1).toEqual([230 { icon: faShoppingCart, id: 'buy_energy', label: 'Buy Energy', path: '/buy_energy' },231 { id: 'producer', label: 'Peter Producer', path: '/buy_energy/producer/1' }232 ]);233 const component = renderComponent();234 expect(usersActions.performGetUserData.mock.calls.length).toEqual(2);235 expect(appActions.performSetupBreadcrumbs.mock.calls.length).toEqual(4);236 component.setProps({ producer: { id: 1, name: 'Test' } });237 component.setProps({ producer: { id: 2, name: 'Test' } });238 expect(appActions.performSetupBreadcrumbs.mock.calls.length).toEqual(6);239 component.setProps({ producer: { id: 2, name: 'Test' } });240 expect(appActions.performSetupBreadcrumbs.mock.calls.length).toEqual(6);241 });242 it('should provide possibility navigate to producers list', () => {243 const component = renderComponent();244 component.setContext(context);245 const back = component.find(Button).at(0);246 back.props().onClick();247 const { push } = context.router.history;248 expect(push.mock.calls.length).toEqual(1);249 const [[route]] = push.mock.calls;250 expect(route).toEqual('/buy_energy');251 });252 it('should provide possibility to select producer', () => {253 const component = renderComponent();254 component.setContext(context);255 const select = component.find(Button).at(1);256 select.props().onClick();257 expect(producersActions.performSelectProducer.mock.calls.length).toEqual(1);258 const [[arg]] = producersActions.performSelectProducer.mock.calls;259 expect(arg).toEqual(1);260 component.setProps({ selectedProducer: { id: 1, message: 'Test' } });261 const { push } = context.router.history;262 expect(push.mock.calls.length).toEqual(1);263 const [[route]] = push.mock.calls;264 expect(route).toEqual('/');265 expect(notificationActions.performPushNotification.mock.calls.length).toEqual(1);266 const [[success]] = notificationActions.performPushNotification.mock.calls;267 expect(success).toEqual({ message: 'test', type: 'success' });268 component.setProps({ error: { message: 'Error Message' } });269 expect(notificationActions.performPushNotification.mock.calls.length).toEqual(2);270 const [, [error]] = notificationActions.performPushNotification.mock.calls;271 expect(error).toEqual({ message: 'test', type: 'error' });272 });273 it('should open buy energy page', () => {274 const component = renderComponent();275 component.setContext(context);276 component.find('BackLink').simulate('click', { preventDefault: jest.fn() });277 expect(context.router.history.push).toHaveBeenCalledWith('/buy_energy');278 });279 it('should calls performSetupLoaderVisibility when receive new loading property', () => {280 const producer = renderComponent();281 producer.setProps({ loading: true });282 expect(appActions.performSetupLoaderVisibility).toHaveBeenCalledWith(expect.anything(), true);283 producer.setProps({ loading: false });284 expect(appActions.performSetupLoaderVisibility).toHaveBeenCalledWith(expect.anything(), false);285 expect(appActions.performSetupLoaderVisibility).toHaveBeenCalledTimes(2);286 });287 it('should setup translated breadcrumbs when locale changed', () => {288 const producer = renderComponent();289 expect(appActions.performSetupBreadcrumbs).toHaveBeenCalledTimes(2);290 producer.setProps({291 locale: 'en'292 });293 expect(appActions.performSetupBreadcrumbs).toHaveBeenCalledTimes(3);294 });...

Full Screen

Full Screen

MyProducer.test.js

Source:MyProducer.test.js Github

copy

Full Screen

1import React from 'react';2import { Provider } from 'react-redux';3import faHome from '@fortawesome/fontawesome-free-solid/faHome';4import { CONTRACT_STATUSES } from '../../../constants';5import MyProducerContainer, { MyProducer } from '../MyProducer';6import { ProducerInfo, Button } from '../../../components';7import { mountWithIntl, shallowWithIntl } from '../../../services/intlTestHelper';8import configureMockStore from 'redux-mock-store';9import * as usersActions from '../../../action_performers/users';10import * as producersActions from '../../../action_performers/producers';11import * as appActions from '../../../action_performers/app';12import * as notificationActions from '../../../action_performers/notifications';13const mockStore = configureMockStore();14const store = mockStore({15 Users: {16 profile: {17 data: {18 user: {19 id: 0,20 firstName: 'string',21 lastName: 'string',22 email: 'string',23 currentProducerId: 1,24 lastBillAvailable: true,25 lastBillAmount: '35.24',26 lastBillDate: 'December;',27 userStatus: 'string',28 workingPrice: 2.3,29 status: 'delivery_net',30 statusCode: CONTRACT_STATUSES.active,31 statusCodeTitle: 'In Supply'32 }33 }34 }35 },36 Producers: {37 producer: {38 data: {39 name: 'Producer',40 price: 2.4,41 annualProduction: 3000,42 purchased: 1300,43 capacity: 8,44 dates: 'Sep 12 - Feb 22',45 tradingStrategy: false,46 id: 1,47 complete: false,48 plantType: 'solar',49 picture: 'https://pbs.twimg.com/profile_images/929933611754708992/ioSgz49P_400x400.jpg',50 location: 'Lippendorf, Neukieritzsch',51 ethereumAddress: '123',52 description: 'desc',53 status: 'active'54 },55 loading: false,56 error: null57 },58 producerHistory: {59 data: [60 {61 date: 'Sep 12',62 value: 'Change amount of energy 3000 kWh'63 },64 {65 date: 'Feb 22',66 value: 'Price change 2.4 ct/kWh'67 },68 {69 date: 'Feb 12',70 value: 'Change amount of energy 2300 kWh'71 },72 {73 date: 'Jan 14',74 value: 'Price change 3 ct/kWh'75 }76 ],77 loading: false,78 error: null79 }80 },81 App: {82 localization: {83 data: {84 locale: 'en'85 }86 }87 }88});89const context = {90 intl: {91 formatMessage: jest.fn()92 },93 router: {94 history: { push: jest.fn() }95 }96};97const props = {98 ...MyProducer.defaultProps,99 producer: {100 id: 1,101 name: 'test'102 },103 producerHistory: [{ date: 'test', value: 'test' }],104 user: {105 id: 1,106 currentProducerId: 1107 },108 error: null109};110function renderContainer() {111 return mountWithIntl(112 <Provider store={store}>113 <MyProducerContainer context={context} />114 </Provider>115 );116}117function renderComponent() {118 return shallowWithIntl(<MyProducer {...props} />, { context });119}120describe('<MyProducer /> Component', () => {121 beforeEach(() => {122 context.router.history.push = jest.fn();123 context.intl.formatMessage = jest.fn();124 context.intl.formatMessage.mockReturnValue('test');125 producersActions.performGetProducer = jest.fn();126 producersActions.performGetProducerHistory = jest.fn();127 appActions.performSetupLoaderVisibility = jest.fn();128 appActions.performSetupBreadcrumbs = jest.fn();129 usersActions.performGetUserData = jest.fn();130 notificationActions.performPushNotification = jest.fn();131 });132 it(`should contains following controls:133 - <section> with class "my-producer-page";134 - 1 <h1>;135 - 1 <Button> component;136 - 1 <ProducerInfo> component";`, () => {137 const component = renderContainer();138 expect(component.find('section.my-producer-page')).toHaveLength(1);139 expect(component.find('h1')).toHaveLength(1);140 expect(component.find(ProducerInfo)).toHaveLength(1);141 expect(component.find(Button)).toHaveLength(1);142 });143 it('should call prepare common function', () => {144 const component = renderContainer();145 const info = component.find(ProducerInfo).at(0);146 expect(info.props()).toEqual({147 description: 'desc',148 details: {149 annualProduction: 3000,150 capacity: 8,151 energyType: 'Solar',152 location: 'Lippendorf, Neukieritzsch',153 name: 'Peter Producer',154 price: 2.4,155 purchased: 1300,156 selectedSince: 'Sep 12 - Feb 22',157 ethereumAddress: '123',158 marketPrice: 2.3,159 status: 'active'160 },161 labels: {162 annualProduction: 'Annual Production',163 capacity: 'Peak Capacity',164 energyType: 'Type of energy',165 location: 'Location',166 name: 'Name',167 price: 'Price',168 marketPrice: 'vs. market price of',169 purchased: 'Energy purchased',170 selectedSince: 'Selected since',171 ethereumAddress: 'Ethereum Address'172 },173 picture: 'https://pbs.twimg.com/profile_images/929933611754708992/ioSgz49P_400x400.jpg'174 });175 });176 it('should returns correct props map', () => {177 const stateDummy = {178 Producers: {179 producer: {180 data: 'producer_data',181 error: null,182 loading: false183 },184 producerHistory: {185 data: 'history_data',186 error: 'test_error',187 loading: 'test_loading'188 }189 },190 Users: {191 profile: {192 data: { user: 'user_data' },193 error: null,194 loading: false195 }196 },197 App: {198 localization: {199 data: {200 locale: 'en'201 }202 }203 }204 };205 const props = MyProducer.mapStateToProps(stateDummy);206 expect(props).toEqual({207 locale: 'en',208 producer: 'producer_data',209 producerHistory: 'history_data',210 user: 'user_data',211 error: 'test_error',212 loading: 'test_loading'213 });214 });215 it('should be rendered only with valid contract status', () => {216 renderContainer();217 });218 it('should perform related actions on did mount step', () => {219 renderContainer();220 expect(usersActions.performGetUserData.mock.calls.length).toEqual(1);221 expect(producersActions.performGetProducer.mock.calls.length).toEqual(1);222 const [[arg1]] = producersActions.performGetProducer.mock.calls;223 expect(arg1).toEqual(1);224 expect(appActions.performSetupBreadcrumbs.mock.calls.length).toEqual(2);225 const [, [bArg1]] = appActions.performSetupBreadcrumbs.mock.calls;226 expect(bArg1).toEqual([227 { icon: faHome, id: '', label: 'Overview', path: '/' },228 { id: 'my_producer', label: 'My Producer', path: '/my_producer' }229 ]);230 const component = renderComponent();231 expect(appActions.performSetupBreadcrumbs.mock.calls.length).toEqual(4);232 expect(usersActions.performGetUserData.mock.calls.length).toEqual(2);233 expect(producersActions.performGetProducer.mock.calls.length).toEqual(2);234 component.setProps({235 user: { currentProducerId: 2, id: 1, statusCode: CONTRACT_STATUSES.active }236 });237 expect(producersActions.performGetProducer.mock.calls.length).toEqual(3);238 component.setProps({239 user: { currentProducerId: 2, id: 2, statusCode: CONTRACT_STATUSES.active }240 });241 expect(producersActions.performGetProducer.mock.calls.length).toEqual(3);242 component.setProps({243 user: { currentProducerId: 1, id: 2, statusCode: CONTRACT_STATUSES.active }244 });245 expect(producersActions.performGetProducer.mock.calls.length).toEqual(4);246 expect(producersActions.performGetProducerHistory.mock.calls.length).toEqual(4);247 component.setContext(context);248 const openProducersList = component.find(Button).at(0);249 openProducersList.props().onClick();250 const { history } = context.router;251 expect(history.push.mock.calls.length).toEqual(1);252 const [[route]] = history.push.mock.calls;253 expect(route).toEqual('/buy_energy');254 component.setProps({ error: { message: 'Error Message' } });255 expect(notificationActions.performPushNotification.mock.calls.length).toEqual(1);256 const [[error]] = notificationActions.performPushNotification.mock.calls;257 expect(error).toEqual({ message: 'test', type: 'error' });258 });259 it('should open trading page', () => {260 const component = renderComponent();261 component.setContext(context);262 component.find('BackLink').simulate('click', { preventDefault: jest.fn() });263 expect(context.router.history.push).toHaveBeenCalledWith('/');264 });265 it('should calls performSetupLoaderVisibility when receive new loading property', () => {266 const myProducer = renderComponent();267 myProducer.setProps({ loading: true });268 expect(appActions.performSetupLoaderVisibility).toHaveBeenCalledWith(expect.anything(), true);269 myProducer.setProps({ loading: false });270 expect(appActions.performSetupLoaderVisibility).toHaveBeenCalledWith(expect.anything(), false);271 expect(appActions.performSetupLoaderVisibility).toHaveBeenCalledTimes(2);272 });273 it('should setup translated breadcrumbs when locale changed', () => {274 const myProducer = renderComponent();275 expect(appActions.performSetupBreadcrumbs).toHaveBeenCalledTimes(2);276 myProducer.setProps({277 locale: 'de'278 });279 expect(appActions.performSetupBreadcrumbs).toHaveBeenCalledTimes(3);280 });...

Full Screen

Full Screen

sailplay.hub.actions.js

Source:sailplay.hub.actions.js Github

copy

Full Screen

1(function () {2 if(typeof window.SAILPLAY === 'undefined'){3 console.log('Can\'t find main SAILPLAY module');4 return;5 }6 var sp = window.SAILPLAY;7 var JSONP = sp.jsonp;8 var _actions_config = false;9 sp.actions = {};10 sp.actions.config = function(){11 return _actions_config;12 };13 //ACTIONS SECTION14 //LOAD ACTIONS LIST15 sp.on('load.actions.list', function () {16 if(sp.config() == {}){17 alert('Please init SailPlay HUB first!');18 return;19 }20 var params = {21 auth_hash: sp.config().auth_hash22 };23 JSONP.get(sp.config().DOMAIN + sp.config().urls.actions.load, params, function (res) {24 // console.dir(res);25 if (res.status == 'ok') {26 _actions_config = res.data;27 sp.send('load.actions.list.success', res.data);28 } else {29 sp.send('load.actions.list.error', res);30 }31 });32 });33 //LOAD ACTIONS LIST34 sp.on('load.actions.custom.list', function () {35 if(sp.config() == {}){36 alert('Please init SailPlay HUB first!');37 return;38 }39 var params = {40 auth_hash: sp.config().auth_hash41 };42 JSONP.get(sp.config().DOMAIN + sp.config().urls.actions.custom.list, params, function (res) {43 // console.dir(res);44 if (res.status == 'ok') {45 sp.send('load.actions.custom.list.success', res.actions);46 } else {47 sp.send('load.actions.custom.list.error', res);48 }49 });50 });51 sp.on('set.actions.list', function (actions) {52 _actions_config = actions;53 });54 //PERFORM ACTION55 sp.actions.parse = function(dom, action){56 if(!sp.is_dom(dom)) {57 console.error('sp.actions.parse() need DOM element as first parameter');58 return;59 }60 if(!action) {61 console.error('sp.actions.parse() need Action object as second parameter');62 return;63 }64 if(!_actions_config.connectedAccounts && !action.force) {65 console.error('sp.actions.parse() must execute after event load.actions.list.success');66 return;67 }68 if(!action.socialType){69 //console.dir(action);70 dom.addEventListener('click', function(){71 sp.send('actions.perform', action);72 });73 return;74 }75 if(sp.config().platform === 'mobile' && action.socialType){76 dom.addEventListener('click', function(){77 sp.send('actions.perform', action);78 });79 }80 else {81 parse_frame();82 }83 function parse_frame(){84 var styles = dom.getAttribute('data-styles');85 var text = dom.getAttribute('data-text');86 var action_frame = document.createElement('IFRAME');87 action_frame.style.border = 'none';88 action_frame.style.width = '150px';89 action_frame.style.height = '30px';90 action_frame.style.background = 'transparent';91 action_frame.style.overflow = 'hidden';92 action_frame.setAttribute('scrolling', 'no');93 var account_connected = action.force ? true : (_actions_config.connectedAccounts[action.socialType] || false);94 action_frame.className = [ 'sailplay_action_frame', (action.socialType || ''), (action.action || ''), (account_connected ? 'account_connected' : '')].join(' ');95 function EncodeQueryData(data)96 {97 var ret = [];98 for (var d in data)99 ret.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));100 return ret.join("&");101 }102 var frame_params = {103 auth_hash: sp.config().auth_hash,104 socialType: action.socialType,105 action: action.action,106 link: action.shortLink,107 pic: (action.pic || _actions_config.partnerCustomPic || sp.config().partner.logo),108 msg: (action.msg || _actions_config.messages[action.action] || sp.config().partner.name),109 account_connected: account_connected,110 force: action.force111 };112 if(action['_actionId']) frame_params._actionId = action._actionId;113 if(styles) frame_params.styles = styles;114 if(text) frame_params.text = text;115 if (action.action == 'purchase') {116 frame_params.purchasePublicKey = _actions_config.purchasePublicKey;117 }118 if (action.action == 'badge') {119 frame_params.badgeId= action.badgeId;120 }121 action_frame.src = sp.config().DOMAIN + '/js-api/' + sp.config().partner.id + '/actions/social-widget/v2/?' + EncodeQueryData(frame_params);122 dom.innerHTML = '';123 dom.appendChild(action_frame);124 action_frame.onload = function() {125 sp.send('actions.parse.success', action);126 };127 //gp speciefied config128 }129 };130 sp.on('actions.parse', function (actions) {131 if(sp.config() == {}){132 return;133 }134 if(actions && Array.isArray(actions)) {135 Actions.social_init(actions);136 }137 else {138 sp.send('actions.parse.error', { message: 'Actions list needed' });139 }140 });141 var Actions = {};142 Actions.social_init = function(actions){143 var social_buttons = document.querySelectorAll('[data-sp-action]');144 for(var i = 0; i < social_buttons.length; i+=1) {145 (function(){146 var btn = social_buttons[i];147 var action_id = Number(btn.getAttribute('data-sp-action'));148 var action = sp.find_by_properties((actions || _actions_config.actions), { _actionId: action_id })[0];149 sp.actions.parse(btn, action);150 }());151 }152 };153 //actions v1 section154 Actions.openSocialRegNeedPopup = function (action) {155 var w;156 if (action.socialType == 'vk')157 w = Actions.popupWindow(_actions_config.social.vk.authUrl, 'social_reg', 840, 400);158 else159 w = Actions.popupWindow(_actions_config.social[action.socialType].authUrl, 'social_reg');160 var checkPopupInterval = setInterval(function () {161 if (w == null || w.closed) {162 sp.send('actions.social.connect.complete');163 clearInterval(checkPopupInterval);164 }165 }, 100);166 };167 Actions.popupWindow = function (url, title, w, h) {168 var width, height, left, top;169 if (w !== undefined && h !== undefined) {170 width = w;171 height = h;172 left = (screen.width / 2) - (w / 2);173 top = (screen.height / 2) - (h / 2);174 } else {175 width = screen.width / 2;176 height = screen.height / 2;177 left = width - (width / 2);178 top = height - (height / 2);179 }180 return window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, copyhistory=no, width=' + width + ', height=' + height + ', top=' + top + ', left=' + left);181 };182 Actions.share = function (action) {183 var frameUrl = sp.config().DOMAIN + '/js-api/' + sp.config().partner.id + '/actions/social-widget/?auth_hash=' + sp.config().auth_hash;184 frameUrl += '&socialType=' + action.socialType + '&action=' + action.action + '&link=' + action.shortLink + '&pic=' + (_actions_config.partnerCustomPic ? _actions_config.partnerCustomPic : sp.config().partner.logo);185 frameUrl += '&msg=' + _actions_config.messages[action.action];186 frameUrl += '&_actionId=' + action['_actionId'];187 if (action.action == 'purchase') {188 frameUrl += '&purchasePublicKey=' + _actions_config.purchasePublicKey;189 }190 191 var width = action.window && action.window.width || 200;192 var height = action.window && action.window.height || 210;193 194 var socialFrame = Actions.popupWindow(frameUrl, 'social_action', width, height);195 var checkPopupInterval = setInterval(function () {196 if (socialFrame == null || socialFrame.closed) {197 sp.send('actions.perform.complete', action);198 clearInterval(checkPopupInterval);199 }200 }, 200);201 };202 Actions.perform = function(action){203 if(sp.config().platform === 'mobile') {204 end_share(action);205 return;206 }207 sp.send('actions.perform.start', action);208 if (action.socialType && _actions_config.connectedAccounts) {209 if (!_actions_config.connectedAccounts[action.socialType]) {210 Actions.openSocialRegNeedPopup(action);211 } else {212 Actions.share(action);213 }214 }215 else if(!action.socialType){216 var frameUrl = sp.config().DOMAIN + '/popup/' + sp.config().partner.id + '/widgets/custom/' + action.type + '/?auth_hash=' + sp.config().auth_hash;217 frameUrl += '&lang=' + sp.config().lang;218 frameUrl += '&from_sdk=0';219 var actionFrame = Actions.popupWindow(frameUrl, 'SailPlay', 600, 400);220 var checkPopupInterval = setInterval(function () {221 if (actionFrame == null || actionFrame.closed) {222 sp.send('actions.perform.complete', action);223 clearInterval(checkPopupInterval);224 }225 }, 200);226 }227 };228 sp.on('actions.perform', function (action, callback) {229 if(sp.config() == {}){230 return;231 }232 if (sp.config().auth_hash) {233 Actions.perform(action, callback);234 } else {235 sp.send('actions.perform.auth.error', action);236 }237 });238 function repair_pic_url(url){239 console.log(url);240 if(/^((http|https|ftp):\/\/)/.test(url)){241 return url;242 }243 if(url.indexOf('//') === 0){244 return window.location.protocol + url;245 }246 else {247 return sp.config().DOMAIN + url;248 }249 }250 function end_share(action){251 var handle_params = {252 partner_id: sp.config().partner.id,253 social_type: action.socialType,254 action: action.action,255 purchase_public_key: _actions_config.purchasePublicKey || '',256 badge_id: action.badgeId || '',257 auth_hash: sp.config().auth_hash,258 platform: sp.config().platform259 };260 sp.jsonp.get(sp.config().DOMAIN + sp.config().urls.actions.handle_social_action, handle_params,261 function(res){262 sp.send('actions.perform.success', { response: res, action: action });263 },264 function(res){265 sp.send('actions.perform.error', { error: res, action: action });266 })267 }...

Full Screen

Full Screen

MyDocuments.test.js

Source:MyDocuments.test.js Github

copy

Full Screen

1import React from 'react';2import { MyDocuments } from '../MyDocuments';3import { shallowWithIntl } from '../../../services/intlTestHelper';4import { DocumentsList } from '../../../components';5import * as notificationsActionPerformers from '../../../action_performers/notifications';6import * as appActions from '../../../action_performers/app';7import * as documentsActions from '../../../action_performers/documents';8import * as usersActions from '../../../action_performers/users';9const DOCUMENTS_MOCKS = [10 { id: 1, type: 'invoice', date: 1521911833, name: 'Invoice.pdf', description: 'Annual bill' },11 { id: 2, type: 'archivedDocument', date: 1521911833, name: 'Monthly Installment.pdf', description: 'Annual bill' },12 { id: 3, type: 'invoice', date: 1521911833, name: 'Annual bill.pdf', description: 'Annual bill' },13 { id: 4, type: 'invoice', date: 1521911833, name: 'Monthly Installment.pdf', description: 'Annual bill' },14 { id: 5, type: 'invoice', date: 1521911833, name: 'Monthly Installment.pdf', description: 'Annual bill' },15 { id: 6, type: 'invoice', date: 1521911833, name: 'Monthly Installment.pdf', description: 'Annual bill' },16 { id: 7, type: 'archivedDocument', date: 1521911833, name: 'Monthly Installment.pdf', description: 'Annual bill' },17 { id: 8, type: undefined, date: undefined, name: undefined, description: undefined }18];19function renderComponent(props = {}, mountFn = shallowWithIntl) {20 return mountFn(<MyDocuments {...props} />);21}22describe('<MyDocuments /> Component', () => {23 jest.useFakeTimers();24 const mainContainerMock = document.createElement('div');25 beforeEach(() => {26 documentsActions.performGetDocuments = jest.fn();27 appActions.performSetupLoaderVisibility = jest.fn();28 documentsActions.performDownloadDocument = jest.fn();29 usersActions.performGetUserData = jest.fn();30 jest.spyOn(document, 'getElementById').mockReturnValue(mainContainerMock);31 jest.spyOn(mainContainerMock, 'addEventListener');32 jest.spyOn(mainContainerMock, 'removeEventListener');33 });34 it('should DocumentsList component with correct props', () => {35 const component = renderComponent({36 documents: DOCUMENTS_MOCKS,37 user: {},38 hasNextDocuments: false,39 documentsLoading: false40 });41 expect(documentsActions.performGetDocuments).toHaveBeenCalledTimes(1);42 expect(component.find(DocumentsList)).toHaveLength(1);43 expect(component.find(DocumentsList).props().documents).toEqual(DOCUMENTS_MOCKS);44 expect(component.find(DocumentsList).props().loading).toEqual(false);45 expect(component.find(DocumentsList).props().pagination).toEqual(true);46 expect(component.find(DocumentsList).props().download).toEqual(expect.any(Function));47 });48 it('should call "performDownloadDocument" action when click download document', () => {49 const component = renderComponent({ documents: DOCUMENTS_MOCKS, user: {} });50 component51 .find(DocumentsList)52 .props()53 .download('url', 'name');54 expect(documentsActions.performDownloadDocument).toHaveBeenCalledWith('url', 'name');55 });56 it('should map state properties', () => {57 const stateMock = {58 Documents: {59 documentsList: {60 loading: true,61 data: { documents: DOCUMENTS_MOCKS, numberOfDocuments: 9 },62 error: 'Error message'63 }64 },65 Users: { profile: { data: { user: 'test_user' }, loading: false } }66 };67 const props = MyDocuments.mapStateToProps(stateMock);68 expect(props.loading).toEqual(stateMock.Documents.documentsList.loading || stateMock.Users.profile.loading);69 expect(props.documentsLoading).toEqual(stateMock.Documents.documentsList.loading);70 expect(props.hasNextDocuments).toEqual(71 stateMock.Documents.documentsList.data.numberOfDocuments >72 stateMock.Documents.documentsList.data.documents.length73 );74 expect(props.documents).toEqual(stateMock.Documents.documentsList.data.documents);75 expect(props.user).toEqual(stateMock.Users.profile.data.user);76 expect(props.error).toEqual(stateMock.Documents.documentsList.error);77 });78 it('should shows server error if smth is failed', () => {79 jest.spyOn(notificationsActionPerformers, 'performPushNotification').mockImplementation(jest.fn());80 const component = renderComponent();81 component.setProps({82 loading: false,83 error: { message: 'Error message' }84 });85 expect(notificationsActionPerformers.performPushNotification).toHaveBeenCalledWith({86 type: 'error',87 message: "Can't load documents from PowerChain web server. Please contact administrator to resolve the error."88 });89 notificationsActionPerformers.performPushNotification.mockRestore();90 });91 it('should calls performSetupLoaderVisibility when receive new loading property', () => {92 const component = renderComponent();93 component.setProps({ loading: true });94 expect(appActions.performSetupLoaderVisibility).toHaveBeenCalledWith(expect.anything(), true);95 component.setProps({ loading: false });96 expect(appActions.performSetupLoaderVisibility).toHaveBeenCalledWith(expect.anything(), false);97 expect(appActions.performSetupLoaderVisibility).toHaveBeenCalledTimes(2);98 });99 it('should calls performGetDocuments when we have new page number', () => {100 const component = renderComponent();101 expect(usersActions.performGetUserData).toHaveBeenCalledTimes(1);102 expect(documentsActions.performGetDocuments).toHaveBeenCalledTimes(1);103 expect(documentsActions.performGetDocuments).toHaveBeenCalledWith(0);104 component.setState({ page: 1 });105 component.update();106 expect(documentsActions.performGetDocuments).toHaveBeenCalledTimes(2);107 expect(documentsActions.performGetDocuments).toHaveBeenCalledWith(1);108 component.setProps({ user: {} });109 component.update();110 expect(documentsActions.performGetDocuments).toHaveBeenCalledTimes(3);111 expect(documentsActions.performGetDocuments).toHaveBeenCalledWith(0);112 component.setProps({ user: {} });113 component.update();114 expect(documentsActions.performGetDocuments).toHaveBeenCalledTimes(4);115 expect(documentsActions.performGetDocuments).toHaveBeenCalledWith(0);116 });117 it('should handler scroll event', () => {118 const component = renderComponent();119 const handleScrollMock = component.instance().scrollHandler;120 expect(mainContainerMock.addEventListener).toHaveBeenCalledWith('scroll', component.instance().scrollHandler);121 component.unmount();122 expect(mainContainerMock.removeEventListener).toHaveBeenCalledWith('scroll', handleScrollMock);123 });124 it('should call scroll handler of the container', () => {125 const showTransactions = renderComponent();126 const dummyEvent = {127 target: {128 scrollTop: 10,129 clientHeight: 10,130 scrollHeight: 10131 }132 };133 showTransactions.setProps({134 hasNextDocuments: true,135 documentsLoading: false136 });137 showTransactions.instance().scrollHandler(dummyEvent);138 jest.runAllTimers();139 expect(showTransactions.state('page')).toBe(1);140 });...

Full Screen

Full Screen

thunks.js

Source:thunks.js Github

copy

Full Screen

1import * as actions from './actions'2import SocketManager from '../services/SocketManager'3import * as DataProvider from '../services/DataProvider'4import * as thunks from './thunks'5import Enums from '../common/enums'6/*7 * Thunk dispatched by "AuthPage" screen. Thunk used to perform authorization.8 */9export const performAuth = () => (dispatch, getState) => {10 let state = getState()11 let reducerState = state.chat12 let email = reducerState.authFormEmail13 let password = reducerState.authFormPassword14 dispatch(actions.performAuth())15 dispatch(actions.performAuthRequest())16 return DataProvider.getOwnerAuth(email, password)17 .then(18 (data) => {19 data.json().then((data) => {20 dispatch(actions.performAuthSuccess(data.data))21 dispatch(thunks.performNavigateToChatListScreen())22 })23 })24 .catch((error) => dispatch(actions.performAuthFailure(error)))25}26/*27 * Thunk used to perform logout.28 */29export const performLogout = () => (dispatch, getState) => {30 let state = getState()31 let reducerState = state.chat32 let ownerToken = reducerState.token33 dispatch(actions.performLogout())34 dispatch(actions.performLogoutRequest())35 DataProvider.getOwnerLogout(ownerToken)36 .then(37 (data) => {38 dispatch(actions.performLogoutSuccess(data))39 dispatch(thunks.performNavigateToAuthScreen())40 },41 (error) => dispatch(actions.performLogoutFailure(error))42 )43}44/*45 * Thunk dispatched by "AuthPage" screen. Thunk used to set auth email.46 */47export const performSetAuthEmail = (email) => (dispatch, getState) => {48 dispatch(actions.performSetAuthEmail(email))49}50/*51 * Thunk dispatched by "AuthPage" screen. Thunk used to set auth name.52 */53export const performSetAuthPassword = (name) => (dispatch, getState) => {54 dispatch(actions.performSetAuthPassword(name))55}56/*57 * Thunk is used for navigate to screens.58 */59export const performChangeScreen = (page) => (dispatch, getState) => {60 dispatch(actions.performChangeScreen(page))61}62/*63 * Thunk calling for navigate to auth page.64 */65export const performNavigateToAuthScreen = () => (dispatch, getState) => {66 let state = getState()67 let reducerState = state.chat68 dispatch(thunks.performChangeScreen(Enums.AppPages.AUTH_PAGE))69}70/*71 * Thunk calling for navigate to chat list screen.72 */73export const performNavigateToChatListScreen = () => (dispatch, getState) => {74 let socket = new SocketManager()75 dispatch(thunks.callChatsList())76 dispatch(thunks.performChangeScreen(Enums.AppPages.CHAT_LIST_PAGE))77}78/*79 * Thunk calling for navigate to chat list screen80 */81export const performNavigateToChatScreen = () => (dispatch, getState) => {82 dispatch(thunks.callGetMessagesList())83 dispatch(thunks.performChangeScreen(Enums.AppPages.CHAT_PAGE))84}85/*86 * Thunk using for send message.87 */88export const callSendMessage = () => (dispatch, getState) => {89 let state = getState()90 let reducerState = state.chat91 let chatId = reducerState.chatId92 let token = reducerState.token93 let message = reducerState.chatInputText94 let socket = new SocketManager()95 socket.sendNewMessage({96 chatId,97 token,98 message,99 callback: () => {100 // Clear input field after send message101 dispatch(thunks.performSetChatInputText(''))102 dispatch(thunks.callGetMessagesList())103 }104 })105}106/*107 * Thunk dispatched by "ChatPage" screen. Thunk set input message text.108 */109export const performSetChatInputText = (text) => (dispatch, getState) => {110 dispatch(actions.performSetChatInputText(text))111}112/*113 * Thunk dispatched by "ChatPage" screen. Thunk call for get message list.114 */115export const callGetMessagesList = () => (dispatch, getState) => {116 let state = getState()117 let reducerState = state.chat118 let chatId = reducerState.chatId119 let token = reducerState.token120 let socket = new SocketManager()121 socket.getChatMessages({122 chatId,123 token,124 callback: (msgList) => dispatch(actions.callGetMessagesListSuccess(msgList))125 })126}127/*128 * Thunk dispatched by "ChatListPage" screen. Thunk call for get chat list.129 */130export const callChatsList = () => (dispatch, getState) => {131 let state = getState()132 let reducerState = state.chat133 let socket = new SocketManager()134 // socket.offChatMessages()135 dispatch(thunks.callGetActiveChatsList())136 dispatch(thunks.callGetWaitingChatsList())137}138/*139 * Thunk dispatched by "ChatListPage" screen. Thunk call for get active chats.140 */141export const callGetActiveChatsList = () => (dispatch, getState) => {142 let state = getState()143 let reducerState = state.chat144 let token = reducerState.token145 let socket = new SocketManager()146 socket.getActiveChats({147 token,148 callback: (data) => dispatch(actions.callGetActiveChatsListSuccess(data.data))149 })150}151/*152 * Thunk dispatched by "ChatListPage" screen. Thunk call for get waiting chats.153 */154export const callGetWaitingChatsList = () => (dispatch, getState) => {155 let state = getState()156 let reducerState = state.chat157 let token = reducerState.token158 let socket = new SocketManager()159 socket.getWaitingChats({160 token,161 callback: (data) => dispatch(actions.callGetWaitingChatsListSuccess(data.data))162 })163}164/*165 * Thunk dispatched by "ChatPageList" screen. Thunk perform for selecting chat and navigate to ChatPage.166 */167export const performSelectChat = (chatId) => (dispatch, getState) => {168 dispatch(actions.performSelectChat(chatId))169 dispatch(thunks.performNavigateToChatScreen())...

Full Screen

Full Screen

chat.js

Source:chat.js Github

copy

Full Screen

1import * as actions from '../actions/actions'2import Enums from '../common/enums'3let initialState = {4 appPage: Enums.AppPages.AUTH_PAGE,5 authRequest: false,6 authSuccess: null,7 authError: null,8 authFormEmail: 'y@ya.ru',9 authFormPassword: '123',10 logoutRequest: false,11 logoutSuccess: null,12 logoutError: null,13 ownerId: null,14 token: null,15 level: null,16 activeChatsList: [],17 waitingChatsList: [],18 isInitChatList: false,19 chatMessagesList: [],20 chatInputText: '',21 chatId: null22}23export default function chat(state = initialState, action) {24 switch (action.type) {25 case actions.PERFORM_AUTH_REQUEST:26 return {27 ...state,28 authRequest: true,29 authSuccess: null,30 authError: null31 }32 case actions.PERFORM_AUTH_SUCCESS:33 return {34 ...state,35 authRequest: false,36 authSuccess: true,37 ownerId: action.payload.data.ownerId,38 token: action.payload.data.token,39 level: action.payload.data.level,40 }41 case actions.PERFORM_AUTH_FAILURE:42 return {43 ...state,44 authRequest: false,45 authError: action.payload.data46 }47 case actions.PERFORM_LOGOUT_REQUEST:48 return {49 ...state,50 logoutRequest: true,51 logoutSuccess: null,52 logoutError: null53 }54 case actions.PERFORM_LOGOUT_SUCCESS:55 return {56 ...state,57 logoutRequest: true,58 logoutSuccess: action.payload.data,59 }60 case actions.PERFORM_LOGOUT_FAILURE:61 return {62 ...state,63 logoutRequest: true,64 logoutError: action.payload.data65 }66 case actions.PERFORM_SET_AUTH_EMAIL:67 return {68 ...state,69 authFormEmail: action.payload.data70 }71 case actions.PERFORM_SET_AUTH_PASSWORD:72 return {73 ...state,74 authFormPassword: action.payload.data75 }76 case actions.PERFORM_CHANGE_SCREEN:77 return {78 ...state,79 appPage: action.payload.data80 }81 case actions.PERFORM_SET_CHAT_INPUT_TEXT:82 return {83 ...state,84 chatInputText: action.payload.data85 }86 case actions.CALL_GET_MESSAGES_LIST_SUCCESS:87 return {88 ...state,89 chatMessagesList: action.payload.data90 }91 case actions.CALL_GET_ACTIVE_CHATS_LIST_SUCCESS:92 return {93 ...state,94 activeChatsList: action.payload.data95 }96 case actions.CALL_GET_WAITING_CHATS_LIST_SUCCESS:97 return {98 ...state,99 waitingChatsList: action.payload.data100 }101 case actions.PERFORM_SELECT_CHAT:102 return {103 ...state,104 chatId: action.payload.data105 }106 default:107 return state108 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1driver.performActions([2 {3 options: {4 }5 },6 {7 options: {8 }9 },10 {11 options: {12 }13 },14 {15 }16]);17driver.releaseActions();18driver.performActions([19 {20 options: {21 }22 },23 {24 options: {25 }26 },27 {28 options: {29 }30 },31 {32 }33]);34driver.releaseActions();35driver.performActions([36 {37 options: {38 }39 },40 {41 options: {42 }43 },44 {45 options: {46 }47 },48 {49 }50]);51driver.releaseActions();52driver.performActions([53 {54 options: {55 }56 },57 {58 options: {59 }60 },61 {62 options: {63 }64 },65 {66 }67]);68driver.releaseActions();69driver.performActions([70 {

Full Screen

Using AI Code Generation

copy

Full Screen

1import io.appium.java_client.MobileElement;2import io.appium.java_client.TouchAction;3import io.appium.java_client.android.AndroidDriver;4import io.appium.java_client.android.AndroidElement;5import io.appium.java_client.touch.offset.PointOption;6import org.openqa.selenium.By;7import org.openqa.selenium.Dimension;8import org.openqa.selenium.WebElement;9import org.openqa.selenium.remote.DesiredCapabilities;10import org.testng.annotations.AfterTest;11import org.testng.annotations.BeforeTest;12import org.testng.annotations.Test;13import java.net.MalformedURLException;14import java.net.URL;15public class TestClass {16 AndroidDriver<AndroidElement> driver;17 public void setup() throws MalformedURLException {18 DesiredCapabilities capabilities = new DesiredCapabilities();19 capabilities.setCapability("BROWSER_NAME", "Android");20 capabilities.setCapability("VERSION", "4.4.2");21 capabilities.setCapability("deviceName","Android Emulator");22 capabilities.setCapability("platformName","Android");23 capabilities.setCapability("appPackage", "com.android.settings");24 capabilities.setCapability("appActivity","com.android.settings.Settings");

Full Screen

Using AI Code Generation

copy

Full Screen

1var actions = driver.actions({bridge: true});2var action = actions.moveTo({x: 100, y: 100});3action.perform();4var actions = driver.actions();5var action = actions.moveTo({x: 100, y: 100});6action.perform();7var actions = driver.actions();8var action = actions.moveTo({x: 100, y: 100});9action.perform();10var action = driver.actions().move({x: 100, y: 100});11action.perform();12var action = driver.actions().move({x: 100, y: 100});13action.perform();14var action = driver.actions().move({x: 100, y: 100});15action.perform();16var action = driver.actions().move({x: 100, y: 100});17action.perform();18var action = driver.actions().move({x: 100, y: 100});19action.perform();20var action = driver.actions().move({x: 100, y: 100});21action.perform();22var action = driver.actions().move({x: 100, y: 100});23action.perform();24var action = driver.actions().move({x: 100, y: 100});25action.perform();26var action = driver.actions().move({x: 100, y: 100});27action.perform();28var action = driver.actions().move({x: 100, y: 100});29action.perform();30var action = driver.actions().move({x: 100, y: 100});31action.perform();32var action = driver.actions().move({x: 100, y: 100});33action.perform();

Full Screen

Using AI Code Generation

copy

Full Screen

1let actions = driver.perform();2actions.touchDown(100, 100).touchMove(200, 200).touchUp(200, 200).perform();3let actions = driver.perform();4actions.touchDown(100, 100).touchMove(200, 200).touchUp(200, 200).perform();5let actions = driver.perform();6actions.touchDown(100, 100).touchMove(200, 200).touchUp(200, 200).perform();7let actions = driver.perform();8actions.touchDown(100, 100).touchMove(200, 200).touchUp(200, 200).perform();9let actions = driver.perform();10actions.touchDown(100, 100).touchMove(200, 200).touchUp(200, 200).perform();11let actions = driver.perform();12actions.touchDown(100, 100).touchMove(200, 200).touchUp(200, 200).perform();13let actions = driver.perform();14actions.touchDown(100, 100).touchMove(200, 200).touchUp(200, 200).perform();15let actions = driver.perform();16actions.touchDown(100, 100).touchMove(200, 200).touchUp(200, 200).perform();17let actions = driver.perform();18actions.touchDown(100, 100).touchMove(200, 200).touchUp(200, 200).perform();19let actions = driver.perform();20actions.touchDown(100, 100).touchMove(200, 200).touchUp(200, 200).perform();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { By } = require('selenium-webdriver');2const { driver } = require('../../../config/wdio.appium.conf');3describe('Appium', () => {4 it('should test the app', async () => {5 await driver.setImplicitWaitTimeout(5000);6 await driver.findElement(By.id('com.example.testapp:id/buttonTest')).click();7 await driver.setImplicitWaitTimeout(5000);8 await driver.findElement(By.id('com.example.testapp:id/buttonStartWebview')).click();9 await driver.setImplicitWaitTimeout(5000);10 await driver.findElement(By.id('com.example.testapp:id/editTextUserInput')).sendKeys('test');11 await driver.setImplicitWaitTimeout(5000);12 await driver.findElement(By.id('com.example.testapp:id/buttonTest')).click();13 await driver.setImplicitWaitTimeout(5000);14 await driver.findElement(By.id('com.example.testapp:id/buttonStartWebview')).click();15 await driver.setImplicitWaitTimeout(5000);16 await driver.findElement(By.id('com.example.testapp:id/editTextUserInput')).sendKeys('test');17 await driver.setImplicitWaitTimeout(5000);18 await driver.findElement(By.id('com.example.testapp:id/buttonTest')).click();19 });20});21const { config } = require('./wdio.shared.conf');22const { join } = require('path');

Full Screen

Using AI Code Generation

copy

Full Screen

1 {2 app: join(process.cwd(), './apps/android-debug.apk'),3 }4];5exports.config = config;6exports.config = {7 capabilities: [{8 }],

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Appium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful