diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 076e345a2a9b16407dc1bbdbffd662405a0b8eba..d72962d2ef4edd82467ad7f2c2503b1fc2763e23 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -1,82 +1,82 @@ -image: docker:git - -services: - - docker:dind - -variables: - DOCKER_DRIVER: overlay2 - DOCKER_TLS_CERTDIR: '' - -stages: - - test - - build - - quality - - publish - -test: - stage: test - image: node:14.15.4 - script: - - yarn - - yarn test --ci --reporters=default --reporters=jest-junit - coverage: /All files[^|]*\|[^|]*\s+([\d\.]+)/ - artifacts: - when: always - reports: - junit: - - junit.xml - only: - - dev - - master - - merge_requests - -build: - stage: build - image: node:14.15.4 - script: - - yarn - - yarn build - only: - - dev - - master - - merge_requests - -build_stack: - stage: build - script: - - docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY - - docker build -t "$CI_REGISTRY_IMAGE/cozy-env:latest" ./docker/ - - docker push $CI_REGISTRY_IMAGE/cozy-env:latest - only: - - master - when: manual - -publish: - stage: publish - image: node:10.15.0 - script: - - yarn cozyPublish - only: - - tags - when: manual - -sonarqube: - stage: quality - only: - - dev - - merge_requests - image: skilldlabs/sonar-scanner:4.0.0 - before_script: - - export NODE_PATH=$NODE_PATH:`npm root -g` - - npm install -g typescript - script: - - > - sonar-scanner - -Dsonar.projectName="ecolyo" - -Dsonar.projectVersion=1.0 - -Dsonar.sourceEncoding=UTF-8 - -Dsonar.projectBaseDir=. - -Dsonar.host.url=${SONAR_URL} - -Dsonar.projectKey=${CI_PROJECT_PATH_SLUG} - -Dsonar.login=${SONAR_TOKEN} - -Dsonar.cpd.exclusions=test/**,src/**/*.spec.ts* +image: docker:git + +services: + - docker:dind + +variables: + DOCKER_DRIVER: overlay2 + DOCKER_TLS_CERTDIR: '' + +stages: + - test + - build + - quality + - publish + +test: + stage: test + image: node:14.15.4-alpine + script: + - yarn + - yarn test --ci --reporters=default --reporters=jest-junit + coverage: /All files[^|]*\|[^|]*\s+([\d\.]+)/ + artifacts: + when: always + reports: + junit: + - junit.xml + only: + - dev + - master + - merge_requests + +build: + stage: build + image: node:14.15.4-alpine + script: + - yarn + - yarn build + only: + - dev + - master + - merge_requests + +build_stack: + stage: build + script: + - docker login -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" $CI_REGISTRY + - docker build -t "$CI_REGISTRY_IMAGE/cozy-env:latest" ./docker/ + - docker push $CI_REGISTRY_IMAGE/cozy-env:latest + only: + - master + when: manual + +publish: + stage: publish + image: node:14.15.4-alpine + script: + - yarn cozyPublish + only: + - tags + when: manual + +sonarqube: + stage: quality + only: + - dev + - merge_requests + image: skilldlabs/sonar-scanner:4.0.0 + before_script: + - export NODE_PATH=$NODE_PATH:`npm root -g` + - npm install -g typescript + script: + - > + sonar-scanner + -Dsonar.projectName="ecolyo" + -Dsonar.projectVersion=1.0 + -Dsonar.sourceEncoding=UTF-8 + -Dsonar.projectBaseDir=. + -Dsonar.host.url=${SONAR_URL} + -Dsonar.projectKey=${CI_PROJECT_PATH_SLUG} + -Dsonar.login=${SONAR_TOKEN} + -Dsonar.cpd.exclusions=test/**,src/**/*.spec.ts* diff --git a/jest.config.js b/jest.config.js index 73b4f796282c9e133891edfb3c22e4429a434a62..6abe3cb94d8e8639ae2515d18c07a578a81a5d1d 100644 --- a/jest.config.js +++ b/jest.config.js @@ -1,10 +1,10 @@ module.exports = { testURL: 'http://localhost/', moduleFileExtensions: ['js', 'jsx', 'ts', 'tsx', 'json', 'styl'], - setupFiles: ['<rootDir>/test/jestLib/setup.js'], + setupFiles: ['<rootDir>/tests/jestLib/setup.js'], moduleDirectories: ['src', 'node_modules'], moduleNameMapper: { - '\\.(png|gif|jpe?g|svg)$': '<rootDir>/test/__mocks__/fileMock.js', + '\\.(png|gif|jpe?g|svg)$': '<rootDir>/tests/__mocks__/fileMock.js', // identity-obj-proxy module is installed by cozy-scripts '\\.(css|styl|sass|scss)$': 'identity-obj-proxy', }, @@ -19,5 +19,5 @@ module.exports = { __ALLOW_HTTP__: false, __TARGET__: 'browser', cozy: {}, - } + }, } diff --git a/src/components/Action/ActionBegin.spec.tsx b/src/components/Action/ActionBegin.spec.tsx index edb03a293da304b93979c7fe279db1e42bfb997a..8c699764c79c307c7576e1016d26bbe15d30a839 100644 --- a/src/components/Action/ActionBegin.spec.tsx +++ b/src/components/Action/ActionBegin.spec.tsx @@ -1,14 +1,14 @@ import React from 'react' import { mount } from 'enzyme' import { Provider } from 'react-redux' -import { globalStateData } from '../../../test/__mocks__/globalStateData.mock' -import { userChallengeData } from '../../../test/__mocks__/userChallengeData.mock' +import { globalStateData } from '../../../tests/__mocks__/globalStateData.mock' +import { userChallengeData } from '../../../tests/__mocks__/userChallengeData.mock' import ActionModal from './ActionModal' import { AllEcogestureData, defaultEcogestureData, -} from '../../../test/__mocks__/actionData.mock' -import { profileData } from '../../../test/__mocks__/profile.mock' +} from '../../../tests/__mocks__/actionData.mock' +import { profileData } from '../../../tests/__mocks__/profile.mock' import configureStore from 'redux-mock-store' import { Button } from '@material-ui/core' import ActionBegin from './ActionBegin' diff --git a/src/components/Action/ActionCard.spec.tsx b/src/components/Action/ActionCard.spec.tsx index 894d5e0b54311448c8ff261236cec0fcc870ca2b..eae3b9b4794bb0dd655282d9e0f9eb9e2d68623c 100644 --- a/src/components/Action/ActionCard.spec.tsx +++ b/src/components/Action/ActionCard.spec.tsx @@ -1,12 +1,12 @@ import React from 'react' import { mount } from 'enzyme' import { Provider } from 'react-redux' -import { globalStateData } from '../../../test/__mocks__/globalStateData.mock' -import { userChallengeData } from '../../../test/__mocks__/userChallengeData.mock' +import { globalStateData } from '../../../tests/__mocks__/globalStateData.mock' +import { userChallengeData } from '../../../tests/__mocks__/userChallengeData.mock' import ActionCard from './ActionCard' -import { profileData } from '../../../test/__mocks__/profile.mock' +import { profileData } from '../../../tests/__mocks__/profile.mock' import configureStore from 'redux-mock-store' -import { defaultEcogestureData } from '../../../test/__mocks__/actionData.mock' +import { defaultEcogestureData } from '../../../tests/__mocks__/actionData.mock' import { Button } from '@material-ui/core' import EcogestureModal from 'components/Ecogesture/EcogestureModal' diff --git a/src/components/Action/ActionChoose.spec.tsx b/src/components/Action/ActionChoose.spec.tsx index 98f134dd67fa191efb6b055127690e1d8262637e..b1b44ff94686f9729773ca2c637d478b4358bd13 100644 --- a/src/components/Action/ActionChoose.spec.tsx +++ b/src/components/Action/ActionChoose.spec.tsx @@ -1,9 +1,9 @@ import React from 'react' import { mount } from 'enzyme' import { Provider } from 'react-redux' -import { globalStateData } from '../../../test/__mocks__/globalStateData.mock' -import { userChallengeData } from '../../../test/__mocks__/userChallengeData.mock' -import { profileData } from '../../../test/__mocks__/profile.mock' +import { globalStateData } from '../../../tests/__mocks__/globalStateData.mock' +import { userChallengeData } from '../../../tests/__mocks__/userChallengeData.mock' +import { profileData } from '../../../tests/__mocks__/profile.mock' import configureStore from 'redux-mock-store' import ActionChoose from './ActionChoose' import ActionBegin from './ActionBegin' diff --git a/src/components/Action/ActionDone.spec.tsx b/src/components/Action/ActionDone.spec.tsx index 1eae02e8d41e0b1665d0485ed1a2a0bc04e2a73a..5b84261409c7ad4f7e4be626ab60721f9da9a015 100644 --- a/src/components/Action/ActionDone.spec.tsx +++ b/src/components/Action/ActionDone.spec.tsx @@ -2,9 +2,9 @@ import React from 'react' import { mount } from 'enzyme' import configureStore from 'redux-mock-store' import { Provider } from 'react-redux' -import { globalStateData } from '../../../test/__mocks__/globalStateData.mock' -import { userChallengeData } from '../../../test/__mocks__/userChallengeData.mock' -import { profileData } from '../../../test/__mocks__/profile.mock' +import { globalStateData } from '../../../tests/__mocks__/globalStateData.mock' +import { userChallengeData } from '../../../tests/__mocks__/userChallengeData.mock' +import { profileData } from '../../../tests/__mocks__/profile.mock' import ActionDone from './ActionDone' import { Button } from '@material-ui/core' import * as reactRedux from 'react-redux' diff --git a/src/components/Action/ActionList.spec.tsx b/src/components/Action/ActionList.spec.tsx index 009e7d02eefb3cee152dca3f9cf05d0df3230ded..34af07b69129d4b2a760cb43aaed7270a00f93e2 100644 --- a/src/components/Action/ActionList.spec.tsx +++ b/src/components/Action/ActionList.spec.tsx @@ -2,12 +2,12 @@ import React from 'react' import { mount } from 'enzyme' import configureStore from 'redux-mock-store' import { Provider } from 'react-redux' -import { globalStateData } from '../../../test/__mocks__/globalStateData.mock' +import { globalStateData } from '../../../tests/__mocks__/globalStateData.mock' import ActionList from './ActionList' import ActionCard from './ActionCard' -import { userChallengeData } from '../../../test/__mocks__/userChallengeData.mock' -import { profileData } from '../../../test/__mocks__/profile.mock' -import { defaultEcogestureData } from '../../../test/__mocks__/actionData.mock' +import { userChallengeData } from '../../../tests/__mocks__/userChallengeData.mock' +import { profileData } from '../../../tests/__mocks__/profile.mock' +import { defaultEcogestureData } from '../../../tests/__mocks__/actionData.mock' const mockStore = configureStore([]) diff --git a/src/components/Action/ActionModal.spec.tsx b/src/components/Action/ActionModal.spec.tsx index bbbd8a9cb1ad53610155d9a1c8e7e811ee06877b..4c868735e27fb4dc0d0d4e7e63cf08cf8c73eacd 100644 --- a/src/components/Action/ActionModal.spec.tsx +++ b/src/components/Action/ActionModal.spec.tsx @@ -1,11 +1,11 @@ import React from 'react' import { mount } from 'enzyme' import { Provider } from 'react-redux' -import { globalStateData } from '../../../test/__mocks__/globalStateData.mock' -import { userChallengeData } from '../../../test/__mocks__/userChallengeData.mock' +import { globalStateData } from '../../../tests/__mocks__/globalStateData.mock' +import { userChallengeData } from '../../../tests/__mocks__/userChallengeData.mock' import ActionModal from './ActionModal' -import { defaultEcogestureData } from '../../../test/__mocks__/actionData.mock' -import { profileData } from '../../../test/__mocks__/profile.mock' +import { defaultEcogestureData } from '../../../tests/__mocks__/actionData.mock' +import { profileData } from '../../../tests/__mocks__/profile.mock' import configureStore from 'redux-mock-store' import { Button } from '@material-ui/core' import * as reactRedux from 'react-redux' diff --git a/src/components/Action/ActionOnGoing.spec.tsx b/src/components/Action/ActionOnGoing.spec.tsx index 7d7b699f9196f79c7522c84a98bb975910aebb8d..ebf49b28b0c3c37579806cce3cc9dcdcd455841f 100644 --- a/src/components/Action/ActionOnGoing.spec.tsx +++ b/src/components/Action/ActionOnGoing.spec.tsx @@ -1,10 +1,10 @@ import React from 'react' import { mount } from 'enzyme' import { Provider } from 'react-redux' -import { globalStateData } from '../../../test/__mocks__/globalStateData.mock' -import { userChallengeData } from '../../../test/__mocks__/userChallengeData.mock' -import { defaultEcogestureData } from '../../../test/__mocks__/actionData.mock' -import { profileData } from '../../../test/__mocks__/profile.mock' +import { globalStateData } from '../../../tests/__mocks__/globalStateData.mock' +import { userChallengeData } from '../../../tests/__mocks__/userChallengeData.mock' +import { defaultEcogestureData } from '../../../tests/__mocks__/actionData.mock' +import { profileData } from '../../../tests/__mocks__/profile.mock' import configureStore from 'redux-mock-store' import { Button } from '@material-ui/core' import ActionOnGoing from './ActionOnGoing' diff --git a/src/components/Action/ActionView.spec.tsx b/src/components/Action/ActionView.spec.tsx index 59a9c30e04a15a7c15f1af271c006e7269e1c811..8442277f410b7c0b37b595374f43322a2aa542e9 100644 --- a/src/components/Action/ActionView.spec.tsx +++ b/src/components/Action/ActionView.spec.tsx @@ -1,16 +1,16 @@ import React from 'react' import { mount } from 'enzyme' import { Provider } from 'react-redux' -import { globalStateData } from '../../../test/__mocks__/globalStateData.mock' -import { userChallengeData } from '../../../test/__mocks__/userChallengeData.mock' +import { globalStateData } from '../../../tests/__mocks__/globalStateData.mock' +import { userChallengeData } from '../../../tests/__mocks__/userChallengeData.mock' import ActionView from 'components/Action/ActionView' import configureStore from 'redux-mock-store' import { UserActionState } from 'enum/userAction.enum' import ActionChoose from './ActionChoose' import ActionOnGoing from './ActionOnGoing' import ActionDone from './ActionDone' -import { profileData } from '../../../test/__mocks__/profile.mock' -import { modalStateData } from '../../../test/__mocks__/modalStateData.mock' +import { profileData } from '../../../tests/__mocks__/profile.mock' +import { modalStateData } from '../../../tests/__mocks__/modalStateData.mock' jest.mock('cozy-ui/transpiled/react/I18n', () => { return { diff --git a/src/components/ActivateHalfHourLoad/ActivateHalfHourLoad.spec.tsx b/src/components/ActivateHalfHourLoad/ActivateHalfHourLoad.spec.tsx index 4fead9d01b5b40f1e0b1284329d0838e22c4160a..ae28dd87d107952e7bc9752615ee3dbc2c90ef86 100644 --- a/src/components/ActivateHalfHourLoad/ActivateHalfHourLoad.spec.tsx +++ b/src/components/ActivateHalfHourLoad/ActivateHalfHourLoad.spec.tsx @@ -1,60 +1,60 @@ -import React from 'react' -import { mount } from 'enzyme' -import ActivateHalfHourLoad from './ActivateHalfHourLoad' -import { Provider } from 'react-redux' -import configureStore from 'redux-mock-store' -import { globalStateData } from '../../../test/__mocks__/globalStateData.mock' -import * as reactRedux from 'react-redux' -import { userChallengeExplo1OnGoing } from '../../../test/__mocks__/userChallengeData.mock' -import MuiButton from '@material-ui/core/Button' - -jest.mock('cozy-ui/transpiled/react/I18n', () => { - return { - useI18n: jest.fn(() => { - return { - t: (str: string) => str, - } - }), - } -}) - -const mockUseSelector = jest.spyOn(reactRedux, 'useSelector') - -const mockConfigureStore = configureStore([]) -const mockStore = mockConfigureStore({ - ecolyo: { - gloabl: globalStateData, - }, -}) - -describe('ActivateHalfHourLoad component test', () => { - it('should open konnector website when button is clicked', () => { - mockUseSelector.mockReturnValue(userChallengeExplo1OnGoing) - - const wrapper = mount( - <Provider store={mockStore}> - <ActivateHalfHourLoad /> - </Provider> - ) - - global.open = jest.fn() - - wrapper.find(MuiButton).simulate('click') - expect(global.open).toHaveBeenCalledWith( - 'https://mon-compte-particulier.enedis.fr/donnees/', - '_blank' - ) - }) - - it('should render correctly ActivatehalfHourLoad', () => { - mockUseSelector.mockReturnValue(userChallengeExplo1OnGoing) - - const wrapper = mount( - <Provider store={mockStore}> - <ActivateHalfHourLoad /> - </Provider> - ) - - expect(wrapper.getElement()).toMatchSnapshot() - }) -}) +import React from 'react' +import { mount } from 'enzyme' +import ActivateHalfHourLoad from './ActivateHalfHourLoad' +import { Provider } from 'react-redux' +import configureStore from 'redux-mock-store' +import { globalStateData } from '../../../tests/__mocks__/globalStateData.mock' +import * as reactRedux from 'react-redux' +import { userChallengeExplo1OnGoing } from '../../../tests/__mocks__/userChallengeData.mock' +import MuiButton from '@material-ui/core/Button' + +jest.mock('cozy-ui/transpiled/react/I18n', () => { + return { + useI18n: jest.fn(() => { + return { + t: (str: string) => str, + } + }), + } +}) + +const mockUseSelector = jest.spyOn(reactRedux, 'useSelector') + +const mockConfigureStore = configureStore([]) +const mockStore = mockConfigureStore({ + ecolyo: { + gloabl: globalStateData, + }, +}) + +describe('ActivateHalfHourLoad component test', () => { + it('should open konnector website when button is clicked', () => { + mockUseSelector.mockReturnValue(userChallengeExplo1OnGoing) + + const wrapper = mount( + <Provider store={mockStore}> + <ActivateHalfHourLoad /> + </Provider> + ) + + global.open = jest.fn() + + wrapper.find(MuiButton).simulate('click') + expect(global.open).toHaveBeenCalledWith( + 'https://mon-compte-particulier.enedis.fr/donnees/', + '_blank' + ) + }) + + it('should render correctly ActivatehalfHourLoad', () => { + mockUseSelector.mockReturnValue(userChallengeExplo1OnGoing) + + const wrapper = mount( + <Provider store={mockStore}> + <ActivateHalfHourLoad /> + </Provider> + ) + + expect(wrapper.getElement()).toMatchSnapshot() + }) +}) diff --git a/src/components/Analysis/AnalysisConsumption.spec.tsx b/src/components/Analysis/AnalysisConsumption.spec.tsx index 73237fd3abe4df763efa007950b056120e00ecf9..2f1157b99c9f0456e8f5e7ba4e930ecd518cae4b 100644 --- a/src/components/Analysis/AnalysisConsumption.spec.tsx +++ b/src/components/Analysis/AnalysisConsumption.spec.tsx @@ -1,381 +1,381 @@ -/* eslint-disable react/display-name */ -import React from 'react' -import { mount } from 'enzyme' -import { Provider } from 'react-redux' -import configureStore from 'redux-mock-store' -import { profileData } from '../../../test/__mocks__/profile.mock' -import AnalysisConsumption from 'components/Analysis/AnalysisConsumption' -import { act } from '@testing-library/react' -import MuiButton from '@material-ui/core/Button' -import StyledCard from 'components/CommonKit/Card/StyledCard' -import { globalStateData } from '../../../test/__mocks__/globalStateData.mock' -import { mockMonthlyForecastJanuaryTestProfile1 } from '../../../test/__mocks__/profileType.mock' -import { FluidType } from 'enum/fluid.enum' -import { PerformanceIndicator } from 'models' - -jest.mock('cozy-ui/transpiled/react/I18n', () => { - return { - useI18n: jest.fn(() => { - return { - t: (str: string) => str, - } - }), - } -}) - -const mockHistoryPush = jest.fn() -jest.mock('react-router-dom', () => ({ - ...jest.requireActual('react-router-dom'), - useHistory: () => ({ - push: mockHistoryPush, - }), -})) - -const mockgetMonthlyForecast = jest.fn() -jest.mock('services/profileType.service', () => { - return jest.fn(() => { - return { - getMonthlyForecast: mockgetMonthlyForecast, - } - }) -}) - -jest.mock('components/Analysis/AnalysisConsumptionRow', () => () => ( - <div id="analysisconsumptionrow"></div> -)) - -const mockStore = configureStore([]) - -const performanceIndicator = { - compareValue: 160.42797399999998, - percentageVariation: 0.026592126632478563, - value: 156.161853, -} -const performanceIndicators = [ - { - compareValue: 203.49, - percentageVariation: 0.12261044768784712, - value: 178.54, - }, - { - compareValue: 7926.82, - percentageVariation: 0.020542916327102145, - value: 7763.98, - }, - { - compareValue: 1316.46, - percentageVariation: -0.0009191316105312541, - value: 1317.67, - }, -] - -describe('AnalysisConsumption component', () => { - it('should be rendered correctly', async () => { - const store = mockStore({ - ecolyo: { - profile: profileData, - global: globalStateData, - }, - }) - const wrapper = mount( - <Provider store={store}> - <AnalysisConsumption - aggregatedPerformanceIndicator={performanceIndicator} - performanceIndicators={performanceIndicators} - /> - </Provider> - ) - await act(async () => { - await new Promise(resolve => setTimeout(resolve)) - wrapper.update() - }) - expect(wrapper.find(StyledCard).exists()).toBeTruthy() - expect(wrapper.find('#analysisconsumptionrow').length).toBe(4) - }) - - it('should be rendered correctly with null aggregated performance indicator', async () => { - const store = mockStore({ - ecolyo: { - profile: profileData, - global: globalStateData, - }, - }) - const mockAggregatedPerformanceIndicator: PerformanceIndicator = { - compareValue: 160.42797399999998, - percentageVariation: null, - value: null, - } - const wrapper = mount( - <Provider store={store}> - <AnalysisConsumption - aggregatedPerformanceIndicator={mockAggregatedPerformanceIndicator} - performanceIndicators={performanceIndicators} - /> - </Provider> - ) - await act(async () => { - await new Promise(resolve => setTimeout(resolve)) - wrapper.update() - }) - expect(wrapper.find(StyledCard).exists()).toBeTruthy() - expect(wrapper.find('#analysisconsumptionrow').length).toBe(4) - }) - - it('should be rendered correctly without fluid and when click on ideal home button', async () => { - const store = mockStore({ - ecolyo: { - profile: profileData, - global: globalStateData, - }, - }) - const wrapper = mount( - <Provider store={store}> - <AnalysisConsumption - aggregatedPerformanceIndicator={performanceIndicator} - performanceIndicators={performanceIndicators} - /> - </Provider> - ) - await act(async () => { - await new Promise(resolve => setTimeout(resolve)) - wrapper.update() - }) - wrapper - .find('.link-ideal') - .first() - .simulate('click') - expect( - wrapper - .find('#analysisconsumptionrow') - .first() - .parent() - .prop('toggleHome') - ).toBe('ideal') - }) - - it('should be rendered correctly without fluid and when click on average home button', async () => { - const store = mockStore({ - ecolyo: { - profile: profileData, - global: globalStateData, - }, - }) - const wrapper = mount( - <Provider store={store}> - <AnalysisConsumption - aggregatedPerformanceIndicator={performanceIndicator} - performanceIndicators={performanceIndicators} - /> - </Provider> - ) - await act(async () => { - await new Promise(resolve => setTimeout(resolve)) - wrapper.update() - }) - wrapper - .find('.link-average') - .first() - .simulate('click') - expect( - wrapper - .find('#analysisconsumptionrow') - .first() - .parent() - .prop('toggleHome') - ).toBe('average') - }) - - it('should be rendered correctly with all fluids connected for ideal', async () => { - const updateGlobalState = { ...globalStateData } - updateGlobalState.fluidTypes = [ - FluidType.ELECTRICITY, - FluidType.WATER, - FluidType.GAS, - ] - const store = mockStore({ - ecolyo: { - profile: profileData, - global: updateGlobalState, - }, - }) - mockgetMonthlyForecast.mockReturnValue( - mockMonthlyForecastJanuaryTestProfile1 - ) - const wrapper = mount( - <Provider store={store}> - <AnalysisConsumption - aggregatedPerformanceIndicator={performanceIndicator} - performanceIndicators={performanceIndicators} - /> - </Provider> - ) - await act(async () => { - await new Promise(resolve => setTimeout(resolve)) - wrapper.update() - }) - expect(mockgetMonthlyForecast).toHaveBeenCalledWith( - profileData.monthlyAnalysisDate.month - 1 - ) - wrapper - .find('.link-ideal') - .first() - .simulate('click') - expect( - wrapper - .find('#analysisconsumptionrow') - .first() - .parent() - .prop('toggleHome') - ).toBe('ideal') - }) - - it('should be rendered correctly with all fluids connected for average', async () => { - const updateGlobalState = { ...globalStateData } - updateGlobalState.fluidTypes = [ - FluidType.ELECTRICITY, - FluidType.WATER, - FluidType.GAS, - ] - const store = mockStore({ - ecolyo: { - profile: profileData, - global: updateGlobalState, - }, - }) - mockgetMonthlyForecast.mockReturnValue( - mockMonthlyForecastJanuaryTestProfile1 - ) - const wrapper = mount( - <Provider store={store}> - <AnalysisConsumption - aggregatedPerformanceIndicator={performanceIndicator} - performanceIndicators={performanceIndicators} - /> - </Provider> - ) - await act(async () => { - await new Promise(resolve => setTimeout(resolve)) - wrapper.update() - }) - expect(mockgetMonthlyForecast).toHaveBeenCalledWith( - profileData.monthlyAnalysisDate.month - 1 - ) - wrapper - .find('.link-average') - .first() - .simulate('click') - expect( - wrapper - .find('#analysisconsumptionrow') - .first() - .parent() - .prop('toggleHome') - ).toBe('average') - }) - - it('should be rendered correctly with 2 fluids connected for ideal', async () => { - const updateGlobalState = { ...globalStateData } - updateGlobalState.fluidTypes = [FluidType.ELECTRICITY, FluidType.WATER] - const store = mockStore({ - ecolyo: { - profile: profileData, - global: updateGlobalState, - }, - }) - mockgetMonthlyForecast.mockReturnValue( - mockMonthlyForecastJanuaryTestProfile1 - ) - const wrapper = mount( - <Provider store={store}> - <AnalysisConsumption - aggregatedPerformanceIndicator={performanceIndicator} - performanceIndicators={performanceIndicators} - /> - </Provider> - ) - await act(async () => { - await new Promise(resolve => setTimeout(resolve)) - wrapper.update() - }) - expect(mockgetMonthlyForecast).toHaveBeenCalledWith( - profileData.monthlyAnalysisDate.month - 1 - ) - wrapper - .find('.link-ideal') - .first() - .simulate('click') - expect( - wrapper - .find('#analysisconsumptionrow') - .first() - .parent() - .prop('toggleHome') - ).toBe('ideal') - }) - - it('should be rendered correctly with 2 fluids connected for average', async () => { - const updateGlobalState = { ...globalStateData } - updateGlobalState.fluidTypes = [FluidType.ELECTRICITY, FluidType.WATER] - const store = mockStore({ - ecolyo: { - profile: profileData, - global: updateGlobalState, - }, - }) - mockgetMonthlyForecast.mockReturnValue( - mockMonthlyForecastJanuaryTestProfile1 - ) - const wrapper = mount( - <Provider store={store}> - <AnalysisConsumption - aggregatedPerformanceIndicator={performanceIndicator} - performanceIndicators={performanceIndicators} - /> - </Provider> - ) - await act(async () => { - await new Promise(resolve => setTimeout(resolve)) - wrapper.update() - }) - expect(mockgetMonthlyForecast).toHaveBeenCalledWith( - profileData.monthlyAnalysisDate.month - 1 - ) - wrapper - .find('.link-average') - .first() - .simulate('click') - expect( - wrapper - .find('#analysisconsumptionrow') - .first() - .parent() - .prop('toggleHome') - ).toBe('average') - }) - - it('should redirect to profileType form when click on mui button', async () => { - const store = mockStore({ - ecolyo: { - profile: profileData, - global: globalStateData, - }, - }) - const wrapper = mount( - <Provider store={store}> - <AnalysisConsumption - aggregatedPerformanceIndicator={performanceIndicator} - performanceIndicators={performanceIndicators} - /> - </Provider> - ) - await act(async () => { - await new Promise(resolve => setTimeout(resolve)) - wrapper.update() - }) - wrapper - .find(MuiButton) - .first() - .simulate('click') - expect(mockHistoryPush).toBeCalledWith('/profileType') - }) -}) +/* eslint-disable react/display-name */ +import React from 'react' +import { mount } from 'enzyme' +import { Provider } from 'react-redux' +import configureStore from 'redux-mock-store' +import { profileData } from '../../../tests/__mocks__/profile.mock' +import AnalysisConsumption from 'components/Analysis/AnalysisConsumption' +import { act } from '@testing-library/react' +import MuiButton from '@material-ui/core/Button' +import StyledCard from 'components/CommonKit/Card/StyledCard' +import { globalStateData } from '../../../tests/__mocks__/globalStateData.mock' +import { mockMonthlyForecastJanuaryTestProfile1 } from '../../../tests/__mocks__/profileType.mock' +import { FluidType } from 'enum/fluid.enum' +import { PerformanceIndicator } from 'models' + +jest.mock('cozy-ui/transpiled/react/I18n', () => { + return { + useI18n: jest.fn(() => { + return { + t: (str: string) => str, + } + }), + } +}) + +const mockHistoryPush = jest.fn() +jest.mock('react-router-dom', () => ({ + ...jest.requireActual('react-router-dom'), + useHistory: () => ({ + push: mockHistoryPush, + }), +})) + +const mockgetMonthlyForecast = jest.fn() +jest.mock('services/profileType.service', () => { + return jest.fn(() => { + return { + getMonthlyForecast: mockgetMonthlyForecast, + } + }) +}) + +jest.mock('components/Analysis/AnalysisConsumptionRow', () => () => ( + <div id="analysisconsumptionrow"></div> +)) + +const mockStore = configureStore([]) + +const performanceIndicator = { + compareValue: 160.42797399999998, + percentageVariation: 0.026592126632478563, + value: 156.161853, +} +const performanceIndicators = [ + { + compareValue: 203.49, + percentageVariation: 0.12261044768784712, + value: 178.54, + }, + { + compareValue: 7926.82, + percentageVariation: 0.020542916327102145, + value: 7763.98, + }, + { + compareValue: 1316.46, + percentageVariation: -0.0009191316105312541, + value: 1317.67, + }, +] + +describe('AnalysisConsumption component', () => { + it('should be rendered correctly', async () => { + const store = mockStore({ + ecolyo: { + profile: profileData, + global: globalStateData, + }, + }) + const wrapper = mount( + <Provider store={store}> + <AnalysisConsumption + aggregatedPerformanceIndicator={performanceIndicator} + performanceIndicators={performanceIndicators} + /> + </Provider> + ) + await act(async () => { + await new Promise(resolve => setTimeout(resolve)) + wrapper.update() + }) + expect(wrapper.find(StyledCard).exists()).toBeTruthy() + expect(wrapper.find('#analysisconsumptionrow').length).toBe(4) + }) + + it('should be rendered correctly with null aggregated performance indicator', async () => { + const store = mockStore({ + ecolyo: { + profile: profileData, + global: globalStateData, + }, + }) + const mockAggregatedPerformanceIndicator: PerformanceIndicator = { + compareValue: 160.42797399999998, + percentageVariation: null, + value: null, + } + const wrapper = mount( + <Provider store={store}> + <AnalysisConsumption + aggregatedPerformanceIndicator={mockAggregatedPerformanceIndicator} + performanceIndicators={performanceIndicators} + /> + </Provider> + ) + await act(async () => { + await new Promise(resolve => setTimeout(resolve)) + wrapper.update() + }) + expect(wrapper.find(StyledCard).exists()).toBeTruthy() + expect(wrapper.find('#analysisconsumptionrow').length).toBe(4) + }) + + it('should be rendered correctly without fluid and when click on ideal home button', async () => { + const store = mockStore({ + ecolyo: { + profile: profileData, + global: globalStateData, + }, + }) + const wrapper = mount( + <Provider store={store}> + <AnalysisConsumption + aggregatedPerformanceIndicator={performanceIndicator} + performanceIndicators={performanceIndicators} + /> + </Provider> + ) + await act(async () => { + await new Promise(resolve => setTimeout(resolve)) + wrapper.update() + }) + wrapper + .find('.link-ideal') + .first() + .simulate('click') + expect( + wrapper + .find('#analysisconsumptionrow') + .first() + .parent() + .prop('toggleHome') + ).toBe('ideal') + }) + + it('should be rendered correctly without fluid and when click on average home button', async () => { + const store = mockStore({ + ecolyo: { + profile: profileData, + global: globalStateData, + }, + }) + const wrapper = mount( + <Provider store={store}> + <AnalysisConsumption + aggregatedPerformanceIndicator={performanceIndicator} + performanceIndicators={performanceIndicators} + /> + </Provider> + ) + await act(async () => { + await new Promise(resolve => setTimeout(resolve)) + wrapper.update() + }) + wrapper + .find('.link-average') + .first() + .simulate('click') + expect( + wrapper + .find('#analysisconsumptionrow') + .first() + .parent() + .prop('toggleHome') + ).toBe('average') + }) + + it('should be rendered correctly with all fluids connected for ideal', async () => { + const updateGlobalState = { ...globalStateData } + updateGlobalState.fluidTypes = [ + FluidType.ELECTRICITY, + FluidType.WATER, + FluidType.GAS, + ] + const store = mockStore({ + ecolyo: { + profile: profileData, + global: updateGlobalState, + }, + }) + mockgetMonthlyForecast.mockReturnValue( + mockMonthlyForecastJanuaryTestProfile1 + ) + const wrapper = mount( + <Provider store={store}> + <AnalysisConsumption + aggregatedPerformanceIndicator={performanceIndicator} + performanceIndicators={performanceIndicators} + /> + </Provider> + ) + await act(async () => { + await new Promise(resolve => setTimeout(resolve)) + wrapper.update() + }) + expect(mockgetMonthlyForecast).toHaveBeenCalledWith( + profileData.monthlyAnalysisDate.month - 1 + ) + wrapper + .find('.link-ideal') + .first() + .simulate('click') + expect( + wrapper + .find('#analysisconsumptionrow') + .first() + .parent() + .prop('toggleHome') + ).toBe('ideal') + }) + + it('should be rendered correctly with all fluids connected for average', async () => { + const updateGlobalState = { ...globalStateData } + updateGlobalState.fluidTypes = [ + FluidType.ELECTRICITY, + FluidType.WATER, + FluidType.GAS, + ] + const store = mockStore({ + ecolyo: { + profile: profileData, + global: updateGlobalState, + }, + }) + mockgetMonthlyForecast.mockReturnValue( + mockMonthlyForecastJanuaryTestProfile1 + ) + const wrapper = mount( + <Provider store={store}> + <AnalysisConsumption + aggregatedPerformanceIndicator={performanceIndicator} + performanceIndicators={performanceIndicators} + /> + </Provider> + ) + await act(async () => { + await new Promise(resolve => setTimeout(resolve)) + wrapper.update() + }) + expect(mockgetMonthlyForecast).toHaveBeenCalledWith( + profileData.monthlyAnalysisDate.month - 1 + ) + wrapper + .find('.link-average') + .first() + .simulate('click') + expect( + wrapper + .find('#analysisconsumptionrow') + .first() + .parent() + .prop('toggleHome') + ).toBe('average') + }) + + it('should be rendered correctly with 2 fluids connected for ideal', async () => { + const updateGlobalState = { ...globalStateData } + updateGlobalState.fluidTypes = [FluidType.ELECTRICITY, FluidType.WATER] + const store = mockStore({ + ecolyo: { + profile: profileData, + global: updateGlobalState, + }, + }) + mockgetMonthlyForecast.mockReturnValue( + mockMonthlyForecastJanuaryTestProfile1 + ) + const wrapper = mount( + <Provider store={store}> + <AnalysisConsumption + aggregatedPerformanceIndicator={performanceIndicator} + performanceIndicators={performanceIndicators} + /> + </Provider> + ) + await act(async () => { + await new Promise(resolve => setTimeout(resolve)) + wrapper.update() + }) + expect(mockgetMonthlyForecast).toHaveBeenCalledWith( + profileData.monthlyAnalysisDate.month - 1 + ) + wrapper + .find('.link-ideal') + .first() + .simulate('click') + expect( + wrapper + .find('#analysisconsumptionrow') + .first() + .parent() + .prop('toggleHome') + ).toBe('ideal') + }) + + it('should be rendered correctly with 2 fluids connected for average', async () => { + const updateGlobalState = { ...globalStateData } + updateGlobalState.fluidTypes = [FluidType.ELECTRICITY, FluidType.WATER] + const store = mockStore({ + ecolyo: { + profile: profileData, + global: updateGlobalState, + }, + }) + mockgetMonthlyForecast.mockReturnValue( + mockMonthlyForecastJanuaryTestProfile1 + ) + const wrapper = mount( + <Provider store={store}> + <AnalysisConsumption + aggregatedPerformanceIndicator={performanceIndicator} + performanceIndicators={performanceIndicators} + /> + </Provider> + ) + await act(async () => { + await new Promise(resolve => setTimeout(resolve)) + wrapper.update() + }) + expect(mockgetMonthlyForecast).toHaveBeenCalledWith( + profileData.monthlyAnalysisDate.month - 1 + ) + wrapper + .find('.link-average') + .first() + .simulate('click') + expect( + wrapper + .find('#analysisconsumptionrow') + .first() + .parent() + .prop('toggleHome') + ).toBe('average') + }) + + it('should redirect to profileType form when click on mui button', async () => { + const store = mockStore({ + ecolyo: { + profile: profileData, + global: globalStateData, + }, + }) + const wrapper = mount( + <Provider store={store}> + <AnalysisConsumption + aggregatedPerformanceIndicator={performanceIndicator} + performanceIndicators={performanceIndicators} + /> + </Provider> + ) + await act(async () => { + await new Promise(resolve => setTimeout(resolve)) + wrapper.update() + }) + wrapper + .find(MuiButton) + .first() + .simulate('click') + expect(mockHistoryPush).toBeCalledWith('/profileType') + }) +}) diff --git a/src/components/Analysis/AnalysisConsumptionRow.spec.tsx b/src/components/Analysis/AnalysisConsumptionRow.spec.tsx index ba20fcf144e1c9ddf71f6cb03cc4866ab52f2a8e..fa4497dc2dca725f0dfd5df5dfeca65309c02b87 100644 --- a/src/components/Analysis/AnalysisConsumptionRow.spec.tsx +++ b/src/components/Analysis/AnalysisConsumptionRow.spec.tsx @@ -1,6 +1,6 @@ import React from 'react' import { mount } from 'enzyme' -import { mockMonthlyForecastJanuaryTestProfile1 } from '../../../test/__mocks__/profileType.mock' +import { mockMonthlyForecastJanuaryTestProfile1 } from '../../../tests/__mocks__/profileType.mock' import { FluidType } from 'enum/fluid.enum' import { MonthlyForecast } from 'models' import AnalysisConsumptionRow from './AnalysisConsumptionRow' diff --git a/src/components/Analysis/AnalysisError.spec.tsx b/src/components/Analysis/AnalysisError.spec.tsx index e72d1f4f8c5c19ce803d8642bac763d485569198..4f4104984a3c60ea152d3ad193af25bd5eb00644 100644 --- a/src/components/Analysis/AnalysisError.spec.tsx +++ b/src/components/Analysis/AnalysisError.spec.tsx @@ -1,81 +1,81 @@ -import React from 'react' -import { mount } from 'enzyme' -import AnalysisError from 'components/Analysis/AnalysisError' -import configureStore from 'redux-mock-store' -import { profileData } from '../../../test/__mocks__/profile.mock' -import { globalStateData } from '../../../test/__mocks__/globalStateData.mock' -import { Provider } from 'react-redux' -import MuiButton from '@material-ui/core/Button' -import Modal from 'components/CommonKit/Modal/Modal' - -jest.mock('cozy-ui/transpiled/react/I18n', () => { - return { - useI18n: jest.fn(() => { - return { - t: (str: string) => str, - } - }), - } -}) -const mockHistoryPush = jest.fn() -const mockHistoryGoBack = jest.fn() -jest.mock('react-router-dom', () => ({ - ...jest.requireActual('react-router-dom'), - useHistory: () => ({ - push: mockHistoryPush, - goBack: mockHistoryGoBack, - }), -})) -const mockStore = configureStore([]) - -describe('AnalysisError component', () => { - it('should be rendered correctly', () => { - const store = mockStore({ - ecolyo: { - profile: profileData, - global: globalStateData, - }, - }) - const wrapper = mount( - <Provider store={store}> - <AnalysisError /> - </Provider> - ) - expect(wrapper.find(Modal).exists()).toBeTruthy() - expect(wrapper.find(MuiButton).exists()).toBeTruthy() - }) - it('should redirect to previous page', () => { - const store = mockStore({ - ecolyo: { - profile: profileData, - global: globalStateData, - }, - }) - const wrapper = mount( - <Provider store={store}> - <AnalysisError /> - </Provider> - ) - wrapper - .find('.btn-secondary-positive') - .first() - .simulate('click') - }) - it('should redirect to options', () => { - const store = mockStore({ - ecolyo: { - profile: profileData, - global: globalStateData, - }, - }) - const wrapper = mount( - <Provider store={store}> - <AnalysisError /> - </Provider> - ) - wrapper - .find('.btn-highlight') - .first() - .simulate('click') - }) -}) +import React from 'react' +import { mount } from 'enzyme' +import AnalysisError from 'components/Analysis/AnalysisError' +import configureStore from 'redux-mock-store' +import { profileData } from '../../../tests/__mocks__/profile.mock' +import { globalStateData } from '../../../tests/__mocks__/globalStateData.mock' +import { Provider } from 'react-redux' +import MuiButton from '@material-ui/core/Button' +import Modal from 'components/CommonKit/Modal/Modal' + +jest.mock('cozy-ui/transpiled/react/I18n', () => { + return { + useI18n: jest.fn(() => { + return { + t: (str: string) => str, + } + }), + } +}) +const mockHistoryPush = jest.fn() +const mockHistoryGoBack = jest.fn() +jest.mock('react-router-dom', () => ({ + ...jest.requireActual('react-router-dom'), + useHistory: () => ({ + push: mockHistoryPush, + goBack: mockHistoryGoBack, + }), +})) +const mockStore = configureStore([]) + +describe('AnalysisError component', () => { + it('should be rendered correctly', () => { + const store = mockStore({ + ecolyo: { + profile: profileData, + global: globalStateData, + }, + }) + const wrapper = mount( + <Provider store={store}> + <AnalysisError /> + </Provider> + ) + expect(wrapper.find(Modal).exists()).toBeTruthy() + expect(wrapper.find(MuiButton).exists()).toBeTruthy() + }) + it('should redirect to previous page', () => { + const store = mockStore({ + ecolyo: { + profile: profileData, + global: globalStateData, + }, + }) + const wrapper = mount( + <Provider store={store}> + <AnalysisError /> + </Provider> + ) + wrapper + .find('.btn-secondary-positive') + .first() + .simulate('click') + }) + it('should redirect to options', () => { + const store = mockStore({ + ecolyo: { + profile: profileData, + global: globalStateData, + }, + }) + const wrapper = mount( + <Provider store={store}> + <AnalysisError /> + </Provider> + ) + wrapper + .find('.btn-highlight') + .first() + .simulate('click') + }) +}) diff --git a/src/components/Analysis/AnalysisView.spec.tsx b/src/components/Analysis/AnalysisView.spec.tsx index eb67641d33befa58c1540ac5acab6f582ccf1442..4fee1caf00e4ec7cabd6c8fc5ab163c83d2fe1a1 100644 --- a/src/components/Analysis/AnalysisView.spec.tsx +++ b/src/components/Analysis/AnalysisView.spec.tsx @@ -1,93 +1,93 @@ -/* eslint-disable react/display-name */ -import React from 'react' -import { mount } from 'enzyme' -import * as reactRedux from 'react-redux' -import { Provider } from 'react-redux' -import AnalysisView from 'components/Analysis/AnalysisView' -import { globalStateData } from '../../../test/__mocks__/globalStateData.mock' -import { profileData } from '../../../test/__mocks__/profile.mock' -import Header from 'components/Header/Header' -import { - createMockStore, - mockInitialEcolyoState, -} from '../../../test/__mocks__/store' -import * as globalActions from 'store/global/global.actions' -import * as profileActions from 'store/profile/profile.actions' - -jest.mock('cozy-ui/transpiled/react/I18n', () => { - return { - useI18n: jest.fn(() => { - return { - t: (str: string) => str, - } - }), - } -}) -jest.mock('components/Header/CozyBar', () => () => <div id="cozybar"></div>) -jest.mock('components/Analysis/MonthlyAnalysis', () => () => ( - <div id="monthlyanalysis"></div> -)) - -const useSelectorSpy = jest.spyOn(reactRedux, 'useSelector') -const useDispatchSpy = jest.spyOn(reactRedux, 'useDispatch') -const toogleAnalysisNotificationSpy = jest.spyOn( - globalActions, - 'toogleAnalysisNotification' -) -const updateProfileSpy = jest.spyOn(profileActions, 'updateProfile') - -describe('AnalysisView component', () => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let store: any - beforeEach(() => { - store = createMockStore(mockInitialEcolyoState) - useSelectorSpy.mockClear() - useDispatchSpy.mockClear() - toogleAnalysisNotificationSpy.mockClear() - updateProfileSpy.mockClear() - }) - - it('should be rendered correctly', () => { - useSelectorSpy.mockReturnValue({ - global: globalStateData, - profile: profileData, - }) - useDispatchSpy.mockReturnValue(jest.fn()) - const wrapper = mount( - <Provider store={store}> - <AnalysisView /> - </Provider> - ) - expect(wrapper.find('#cozybar')).toBeTruthy() - expect(wrapper.find(Header)).toBeTruthy() - expect(wrapper.find('#monthlyanalysis')).toBeTruthy() - }) - - it('should update profile and toogle analysis notification to false if notification is true', () => { - useSelectorSpy.mockReturnValue({ - global: { - ...globalStateData, - analysisNotification: true, - }, - profile: { - ...profileData, - haveSeenLastAnalysis: false, - }, - }) - useDispatchSpy.mockReturnValue(jest.fn()) - const wrapper = mount( - <Provider store={store}> - <AnalysisView /> - </Provider> - ) - expect(wrapper.find('#cozybar')).toBeTruthy() - expect(wrapper.find(Header)).toBeTruthy() - expect(wrapper.find('#monthlyanalysis')).toBeTruthy() - expect(updateProfileSpy).toBeCalledTimes(1) - expect(updateProfileSpy).toHaveBeenCalledWith({ - haveSeenLastAnalysis: true, - }) - expect(toogleAnalysisNotificationSpy).toBeCalledTimes(1) - expect(toogleAnalysisNotificationSpy).toHaveBeenCalledWith(false) - }) -}) +/* eslint-disable react/display-name */ +import React from 'react' +import { mount } from 'enzyme' +import * as reactRedux from 'react-redux' +import { Provider } from 'react-redux' +import AnalysisView from 'components/Analysis/AnalysisView' +import { globalStateData } from '../../../tests/__mocks__/globalStateData.mock' +import { profileData } from '../../../tests/__mocks__/profile.mock' +import Header from 'components/Header/Header' +import { + createMockStore, + mockInitialEcolyoState, +} from '../../../tests/__mocks__/store' +import * as globalActions from 'store/global/global.actions' +import * as profileActions from 'store/profile/profile.actions' + +jest.mock('cozy-ui/transpiled/react/I18n', () => { + return { + useI18n: jest.fn(() => { + return { + t: (str: string) => str, + } + }), + } +}) +jest.mock('components/Header/CozyBar', () => () => <div id="cozybar"></div>) +jest.mock('components/Analysis/MonthlyAnalysis', () => () => ( + <div id="monthlyanalysis"></div> +)) + +const useSelectorSpy = jest.spyOn(reactRedux, 'useSelector') +const useDispatchSpy = jest.spyOn(reactRedux, 'useDispatch') +const toogleAnalysisNotificationSpy = jest.spyOn( + globalActions, + 'toogleAnalysisNotification' +) +const updateProfileSpy = jest.spyOn(profileActions, 'updateProfile') + +describe('AnalysisView component', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let store: any + beforeEach(() => { + store = createMockStore(mockInitialEcolyoState) + useSelectorSpy.mockClear() + useDispatchSpy.mockClear() + toogleAnalysisNotificationSpy.mockClear() + updateProfileSpy.mockClear() + }) + + it('should be rendered correctly', () => { + useSelectorSpy.mockReturnValue({ + global: globalStateData, + profile: profileData, + }) + useDispatchSpy.mockReturnValue(jest.fn()) + const wrapper = mount( + <Provider store={store}> + <AnalysisView /> + </Provider> + ) + expect(wrapper.find('#cozybar')).toBeTruthy() + expect(wrapper.find(Header)).toBeTruthy() + expect(wrapper.find('#monthlyanalysis')).toBeTruthy() + }) + + it('should update profile and toogle analysis notification to false if notification is true', () => { + useSelectorSpy.mockReturnValue({ + global: { + ...globalStateData, + analysisNotification: true, + }, + profile: { + ...profileData, + haveSeenLastAnalysis: false, + }, + }) + useDispatchSpy.mockReturnValue(jest.fn()) + const wrapper = mount( + <Provider store={store}> + <AnalysisView /> + </Provider> + ) + expect(wrapper.find('#cozybar')).toBeTruthy() + expect(wrapper.find(Header)).toBeTruthy() + expect(wrapper.find('#monthlyanalysis')).toBeTruthy() + expect(updateProfileSpy).toBeCalledTimes(1) + expect(updateProfileSpy).toHaveBeenCalledWith({ + haveSeenLastAnalysis: true, + }) + expect(toogleAnalysisNotificationSpy).toBeCalledTimes(1) + expect(toogleAnalysisNotificationSpy).toHaveBeenCalledWith(false) + }) +}) diff --git a/src/components/Analysis/MonthlyAnalysis.spec.tsx b/src/components/Analysis/MonthlyAnalysis.spec.tsx index 7e6316525328617ef3f7d2fa546c6851f5847a71..3f8bfbecbfa97c368cea17c2d4eea8d7d76607d7 100644 --- a/src/components/Analysis/MonthlyAnalysis.spec.tsx +++ b/src/components/Analysis/MonthlyAnalysis.spec.tsx @@ -1,36 +1,36 @@ -import React from 'react' -import { shallow } from 'enzyme' - -import MonthlyAnalysis from 'components/Analysis/MonthlyAnalysis' -import { DateTime } from 'luxon' - -import * as reactRedux from 'react-redux' -import { userChallengeExplo1OnGoing } from '../../../test/__mocks__/userChallengeData.mock' - -jest.mock('cozy-ui/transpiled/react/I18n', () => { - return { - useI18n: jest.fn(() => { - return { - t: (str: string) => str, - } - }), - } -}) - -const mockUseSelector = jest.spyOn(reactRedux, 'useSelector') - -const analysisDate = DateTime.fromISO('2020-11-17T00:00:00.000+01:00') -describe('MonthlyAnalysis component', () => { - mockUseSelector.mockReturnValue(userChallengeExplo1OnGoing) - const setAnalysisDate = jest.fn() - const setLoad = jest.fn() - const useStateSpy = jest.spyOn(React, 'useState') - const useStateMock: any = (init: any) => [analysisDate, setAnalysisDate] - const useStateLoad: any = (init: any) => [true, setLoad] - useStateSpy.mockImplementationOnce(useStateMock) - useStateSpy.mockImplementationOnce(useStateLoad) - it('should be rendered correctly', () => { - const component = shallow(<MonthlyAnalysis />).getElement() - expect(component).toMatchSnapshot() - }) -}) +import React from 'react' +import { shallow } from 'enzyme' + +import MonthlyAnalysis from 'components/Analysis/MonthlyAnalysis' +import { DateTime } from 'luxon' + +import * as reactRedux from 'react-redux' +import { userChallengeExplo1OnGoing } from '../../../tests/__mocks__/userChallengeData.mock' + +jest.mock('cozy-ui/transpiled/react/I18n', () => { + return { + useI18n: jest.fn(() => { + return { + t: (str: string) => str, + } + }), + } +}) + +const mockUseSelector = jest.spyOn(reactRedux, 'useSelector') + +const analysisDate = DateTime.fromISO('2020-11-17T00:00:00.000+01:00') +describe('MonthlyAnalysis component', () => { + mockUseSelector.mockReturnValue(userChallengeExplo1OnGoing) + const setAnalysisDate = jest.fn() + const setLoad = jest.fn() + const useStateSpy = jest.spyOn(React, 'useState') + const useStateMock: any = (init: any) => [analysisDate, setAnalysisDate] + const useStateLoad: any = (init: any) => [true, setLoad] + useStateSpy.mockImplementationOnce(useStateMock) + useStateSpy.mockImplementationOnce(useStateLoad) + it('should be rendered correctly', () => { + const component = shallow(<MonthlyAnalysis />).getElement() + expect(component).toMatchSnapshot() + }) +}) diff --git a/src/components/Challenge/ChallengeCard.spec.tsx b/src/components/Challenge/ChallengeCard.spec.tsx index 86f1682620001fe148fe1b9902e044009ada036d..d481a4d2a81665e1c4dcf4e5a948fd6abb9fa2bf 100644 --- a/src/components/Challenge/ChallengeCard.spec.tsx +++ b/src/components/Challenge/ChallengeCard.spec.tsx @@ -4,7 +4,7 @@ import ChallengeCard from './ChallengeCard' import ChallengeCardLocked from './ChallengeCardLocked' import ChallengeCardUnlocked from './ChallengeCardUnlocked' import ChallengeCardOnGoing from './ChallengeCardOnGoing' -import { userChallengeData } from '../../../test/__mocks__/userChallengeData.mock' +import { userChallengeData } from '../../../tests/__mocks__/userChallengeData.mock' jest.mock('cozy-ui/transpiled/react/I18n', () => { return { diff --git a/src/components/Challenge/ChallengeCardDone.spec.tsx b/src/components/Challenge/ChallengeCardDone.spec.tsx index 140be575db79eb62e9afbe7d9d6dc617735814fc..684c9d3355e542406ee7559624e56b83e61f2afb 100644 --- a/src/components/Challenge/ChallengeCardDone.spec.tsx +++ b/src/components/Challenge/ChallengeCardDone.spec.tsx @@ -1,23 +1,23 @@ -import React from 'react' -import { shallow } from 'enzyme' -import ChallengeCardDone from 'components/Challenge/ChallengeCardDone' -import { userChallengeData } from '../../../test/__mocks__/userChallengeData.mock' - -jest.mock('cozy-ui/transpiled/react/I18n', () => { - return { - useI18n: jest.fn(() => { - return { - t: (str: string) => str, - } - }), - } -}) - -describe('ChallengeCardDone component', () => { - it('should be rendered correctly', () => { - const component = shallow( - <ChallengeCardDone userChallenge={userChallengeData[0]} /> - ).getElement() - expect(component).toMatchSnapshot() - }) -}) +import React from 'react' +import { shallow } from 'enzyme' +import ChallengeCardDone from 'components/Challenge/ChallengeCardDone' +import { userChallengeData } from '../../../tests/__mocks__/userChallengeData.mock' + +jest.mock('cozy-ui/transpiled/react/I18n', () => { + return { + useI18n: jest.fn(() => { + return { + t: (str: string) => str, + } + }), + } +}) + +describe('ChallengeCardDone component', () => { + it('should be rendered correctly', () => { + const component = shallow( + <ChallengeCardDone userChallenge={userChallengeData[0]} /> + ).getElement() + expect(component).toMatchSnapshot() + }) +}) diff --git a/src/components/Challenge/ChallengeCardLocked.spec.tsx b/src/components/Challenge/ChallengeCardLocked.spec.tsx index 76c52d839460a45b9b48c80d0b6da8dcb33e49bd..84fee1557824212f28c305867f4d42d2a9869718 100644 --- a/src/components/Challenge/ChallengeCardLocked.spec.tsx +++ b/src/components/Challenge/ChallengeCardLocked.spec.tsx @@ -1,23 +1,23 @@ -import React from 'react' -import { shallow } from 'enzyme' -import ChallengeCardLocked from './ChallengeCardLocked' -import { userChallengeData } from '../../../test/__mocks__/userChallengeData.mock' - -jest.mock('cozy-ui/transpiled/react/I18n', () => { - return { - useI18n: jest.fn(() => { - return { - t: (str: string) => str, - } - }), - } -}) -//TODO fis MUI theme error -describe('ChallengeCardLocked component', () => { - it('should be rendered correctly', () => { - const component = shallow( - <ChallengeCardLocked userChallenge={userChallengeData[3]} /> - ).getElement() - expect(component).toMatchSnapshot() - }) -}) +import React from 'react' +import { shallow } from 'enzyme' +import ChallengeCardLocked from './ChallengeCardLocked' +import { userChallengeData } from '../../../tests/__mocks__/userChallengeData.mock' + +jest.mock('cozy-ui/transpiled/react/I18n', () => { + return { + useI18n: jest.fn(() => { + return { + t: (str: string) => str, + } + }), + } +}) +//TODO fis MUI theme error +describe('ChallengeCardLocked component', () => { + it('should be rendered correctly', () => { + const component = shallow( + <ChallengeCardLocked userChallenge={userChallengeData[3]} /> + ).getElement() + expect(component).toMatchSnapshot() + }) +}) diff --git a/src/components/Challenge/ChallengeCardUnlocked.spec.tsx b/src/components/Challenge/ChallengeCardUnlocked.spec.tsx index f939ea5e7e01f85e7a4a16457583c0081696c90d..e0d0f86a92831c6558632ad68c11da4b8b42d342 100644 --- a/src/components/Challenge/ChallengeCardUnlocked.spec.tsx +++ b/src/components/Challenge/ChallengeCardUnlocked.spec.tsx @@ -3,8 +3,8 @@ import { mount } from 'enzyme' import { Provider } from 'react-redux' import configureStore from 'redux-mock-store' import ChallengeCardUnlocked from './ChallengeCardUnlocked' -import { userChallengeData } from '../../../test/__mocks__/userChallengeData.mock' -import { globalStateData } from '../../../test/__mocks__/globalStateData.mock' +import { userChallengeData } from '../../../tests/__mocks__/userChallengeData.mock' +import { globalStateData } from '../../../tests/__mocks__/globalStateData.mock' import ChallengeNoFluidModal from './ChallengeNoFluidModal' import { FluidType } from 'enum/fluid.enum' diff --git a/src/components/Challenge/ChallengeView.spec.tsx b/src/components/Challenge/ChallengeView.spec.tsx index 7f4d141bacce3e564030f7df2ff90c0f606fd435..2d3e3d39e797086758e8b9c393c3976e75465101 100644 --- a/src/components/Challenge/ChallengeView.spec.tsx +++ b/src/components/Challenge/ChallengeView.spec.tsx @@ -1,15 +1,15 @@ -import React from 'react' -import { shallow } from 'enzyme' -import ChallengeView from 'components/Challenge/ChallengeView' -import * as reactRedux from 'react-redux' -import { challengeStateDataFull } from '../../../test/__mocks__/challengeStateData.mock' - -const mockUseSelector = jest.spyOn(reactRedux, 'useSelector') - -describe('ChallengeView component', () => { - it('should be rendered correctly', () => { - mockUseSelector.mockReturnValue(challengeStateDataFull) - const component = shallow(<ChallengeView />).getElement() - expect(component).toMatchSnapshot() - }) -}) +import React from 'react' +import { shallow } from 'enzyme' +import ChallengeView from 'components/Challenge/ChallengeView' +import * as reactRedux from 'react-redux' +import { challengeStateDataFull } from '../../../tests/__mocks__/challengeStateData.mock' + +const mockUseSelector = jest.spyOn(reactRedux, 'useSelector') + +describe('ChallengeView component', () => { + it('should be rendered correctly', () => { + mockUseSelector.mockReturnValue(challengeStateDataFull) + const component = shallow(<ChallengeView />).getElement() + expect(component).toMatchSnapshot() + }) +}) diff --git a/src/components/Charts/AxisBottom.spec.tsx b/src/components/Charts/AxisBottom.spec.tsx index f186c8ea952e5cff848add1a5be8522ff004a527..871824baa987cc934fd9f2a6cbb0f883822ee7f0 100644 --- a/src/components/Charts/AxisBottom.spec.tsx +++ b/src/components/Charts/AxisBottom.spec.tsx @@ -1,110 +1,110 @@ -import React from 'react' -import AxisBottom from './AxisBottom' -import { mount } from 'enzyme' -import { Provider } from 'react-redux' -import * as reactRedux from 'react-redux' -import { - createMockStore, - mockInitialEcolyoState, -} from '../../../test/__mocks__/store' -import { graphData } from '../../../test/__mocks__/datachartData.mock' -import { TimeStep } from 'enum/timeStep.enum' -import { DateTime } from 'luxon' -import { scaleBand, ScaleBand } from 'd3-scale' - -const mockXScale: ScaleBand<string> = scaleBand() - .domain(['0', '10']) - .range([0, 100]) - .padding(0.2) - -const mockProps = { - data: graphData.actualData, - xScale: mockXScale, - height: 20, - marginLeft: 10, - marginBottom: 10, -} - -const useSelectorSpy = jest.spyOn(reactRedux, 'useSelector') -const useDispatchSpy = jest.spyOn(reactRedux, 'useDispatch') - -describe('AxisBottom component test', () => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let store: any - beforeEach(() => { - store = createMockStore(mockInitialEcolyoState) - useDispatchSpy.mockClear() - }) - - useSelectorSpy.mockReturnValue({ - selectedDate: DateTime.fromISO('2020-10-01T00:00:00.000Z', { - zone: 'utc', - }), - }) - - it('should correctly render YEAR format of AxisBottom', () => { - const wrapper = mount( - <Provider store={store}> - <svg> - <AxisBottom {...mockProps} timeStep={TimeStep.YEAR} /> - </svg> - </Provider> - ) - expect(wrapper.getElement()).toMatchSnapshot() - }) - - it('should correctly render MONTH format of AxisBottom', () => { - const wrapper = mount( - <Provider store={store}> - <svg> - <AxisBottom {...mockProps} timeStep={TimeStep.MONTH} /> - </svg> - </Provider> - ) - expect(wrapper.getElement()).toMatchSnapshot() - }) - - it('should correctly render DAY format of AxisBottom without duel', () => { - const wrapper = mount( - <Provider store={store}> - <svg> - <AxisBottom {...mockProps} timeStep={TimeStep.DAY} /> - </svg> - </Provider> - ) - expect(wrapper.getElement()).toMatchSnapshot() - }) - - it('should correctly render DAY format of AxisBottom with duel', () => { - const wrapper = mount( - <Provider store={store}> - <svg> - <AxisBottom {...mockProps} timeStep={TimeStep.DAY} isDuel={true} /> - </svg> - </Provider> - ) - expect(wrapper.getElement()).toMatchSnapshot() - }) - - it('should correctly render WEEK format of AxisBottom', () => { - const wrapper = mount( - <Provider store={store}> - <svg> - <AxisBottom {...mockProps} timeStep={TimeStep.WEEK} /> - </svg> - </Provider> - ) - expect(wrapper.getElement()).toMatchSnapshot() - }) - - it('should correctly render HALF_AN_HOUR format of AxisBottom', () => { - const wrapper = mount( - <Provider store={store}> - <svg> - <AxisBottom {...mockProps} timeStep={TimeStep.HALF_AN_HOUR} /> - </svg> - </Provider> - ) - expect(wrapper.getElement()).toMatchSnapshot() - }) -}) +import React from 'react' +import AxisBottom from './AxisBottom' +import { mount } from 'enzyme' +import { Provider } from 'react-redux' +import * as reactRedux from 'react-redux' +import { + createMockStore, + mockInitialEcolyoState, +} from '../../../tests/__mocks__/store' +import { graphData } from '../../../tests/__mocks__/datachartData.mock' +import { TimeStep } from 'enum/timeStep.enum' +import { DateTime } from 'luxon' +import { scaleBand, ScaleBand } from 'd3-scale' + +const mockXScale: ScaleBand<string> = scaleBand() + .domain(['0', '10']) + .range([0, 100]) + .padding(0.2) + +const mockProps = { + data: graphData.actualData, + xScale: mockXScale, + height: 20, + marginLeft: 10, + marginBottom: 10, +} + +const useSelectorSpy = jest.spyOn(reactRedux, 'useSelector') +const useDispatchSpy = jest.spyOn(reactRedux, 'useDispatch') + +describe('AxisBottom component test', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let store: any + beforeEach(() => { + store = createMockStore(mockInitialEcolyoState) + useDispatchSpy.mockClear() + }) + + useSelectorSpy.mockReturnValue({ + selectedDate: DateTime.fromISO('2020-10-01T00:00:00.000Z', { + zone: 'utc', + }), + }) + + it('should correctly render YEAR format of AxisBottom', () => { + const wrapper = mount( + <Provider store={store}> + <svg> + <AxisBottom {...mockProps} timeStep={TimeStep.YEAR} /> + </svg> + </Provider> + ) + expect(wrapper.getElement()).toMatchSnapshot() + }) + + it('should correctly render MONTH format of AxisBottom', () => { + const wrapper = mount( + <Provider store={store}> + <svg> + <AxisBottom {...mockProps} timeStep={TimeStep.MONTH} /> + </svg> + </Provider> + ) + expect(wrapper.getElement()).toMatchSnapshot() + }) + + it('should correctly render DAY format of AxisBottom without duel', () => { + const wrapper = mount( + <Provider store={store}> + <svg> + <AxisBottom {...mockProps} timeStep={TimeStep.DAY} /> + </svg> + </Provider> + ) + expect(wrapper.getElement()).toMatchSnapshot() + }) + + it('should correctly render DAY format of AxisBottom with duel', () => { + const wrapper = mount( + <Provider store={store}> + <svg> + <AxisBottom {...mockProps} timeStep={TimeStep.DAY} isDuel={true} /> + </svg> + </Provider> + ) + expect(wrapper.getElement()).toMatchSnapshot() + }) + + it('should correctly render WEEK format of AxisBottom', () => { + const wrapper = mount( + <Provider store={store}> + <svg> + <AxisBottom {...mockProps} timeStep={TimeStep.WEEK} /> + </svg> + </Provider> + ) + expect(wrapper.getElement()).toMatchSnapshot() + }) + + it('should correctly render HALF_AN_HOUR format of AxisBottom', () => { + const wrapper = mount( + <Provider store={store}> + <svg> + <AxisBottom {...mockProps} timeStep={TimeStep.HALF_AN_HOUR} /> + </svg> + </Provider> + ) + expect(wrapper.getElement()).toMatchSnapshot() + }) +}) diff --git a/src/components/Charts/Bar.spec.tsx b/src/components/Charts/Bar.spec.tsx index 9988cc5a2b6a7128f96c9a45fe3bac865d454e73..76e3f1a904e5acacd18d15a52192dead5ad2b7fb 100644 --- a/src/components/Charts/Bar.spec.tsx +++ b/src/components/Charts/Bar.spec.tsx @@ -1,158 +1,158 @@ -import React from 'react' -import { mount } from 'enzyme' -import { Provider } from 'react-redux' -import * as reactRedux from 'react-redux' -import { - createMockStore, - mockInitialEcolyoState, -} from '../../../test/__mocks__/store' -import * as chartActions from 'store/chart/chart.actions' -import Bar from './Bar' -import { FluidType } from 'enum/fluid.enum' -import { TimeStep } from 'enum/timeStep.enum' -import { graphData } from '../../../test/__mocks__/datachartData.mock' -import { DateTime } from 'luxon' -import { scaleBand, ScaleBand, scaleLinear } from 'd3' - -const mockXScale: ScaleBand<string> = scaleBand() - .domain( - graphData.actualData.map(d => - d.date.toLocaleString(DateTime.DATETIME_SHORT) - ) - ) - .range([0, 10]) - .padding(0.2) - -const mockParam = { - index: 4, - dataload: graphData.actualData[0], - compareDataload: graphData.actualData[1], - fluidType: FluidType.MULTIFLUID, - timeStep: TimeStep.DAY, - showCompare: false, - xScale: mockXScale, - yScale: scaleLinear(), - height: 20, - isSwitching: false, - isDuel: false, -} - -const useSelectorSpy = jest.spyOn(reactRedux, 'useSelector') -const useDispatchSpy = jest.spyOn(reactRedux, 'useDispatch') -const setSelectedDateSpy = jest.spyOn(chartActions, 'setSelectedDate') -const setCurrentDatachartIndexSpy = jest.spyOn( - chartActions, - 'setCurrentDatachartIndex' -) - -describe('Bar component test', () => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let store: any - beforeEach(() => { - store = createMockStore(mockInitialEcolyoState) - useDispatchSpy.mockClear() - setSelectedDateSpy.mockClear() - setCurrentDatachartIndexSpy.mockClear() - }) - - useSelectorSpy.mockReturnValue({ - selectedDate: DateTime.fromISO('2020-10-01T00:00:00.000Z', { - zone: 'utc', - }), - }) - - it('should correctly render Multifluid Bar', () => { - const wrapper = mount( - <Provider store={store}> - <svg> - <Bar {...mockParam} /> - </svg> - </Provider> - ) - expect(wrapper.getElement()).toMatchSnapshot() - }) - - it('should correctly render Electricity Bar', () => { - const wrapper = mount( - <Provider store={store}> - <svg> - <Bar {...mockParam} fluidType={FluidType.ELECTRICITY} /> - </svg> - </Provider> - ) - expect(wrapper.getElement()).toMatchSnapshot() - }) - - it('should correctly render Water Bar', () => { - const wrapper = mount( - <Provider store={store}> - <svg> - <Bar {...mockParam} fluidType={FluidType.WATER} /> - </svg> - </Provider> - ) - expect(wrapper.getElement()).toMatchSnapshot() - }) - - it('should correctly render Gas Bar', () => { - const wrapper = mount( - <Provider store={store}> - <svg> - <Bar {...mockParam} fluidType={FluidType.GAS} /> - </svg> - </Provider> - ) - expect(wrapper.getElement()).toMatchSnapshot() - }) - - it('should correctly render Bar with showCompare', () => { - const wrapper = mount( - <Provider store={store}> - <svg> - <Bar {...mockParam} showCompare={true} /> - </svg> - </Provider> - ) - expect(wrapper.getElement()).toMatchSnapshot() - }) - - it('should correctly render Bar with isSwitching', () => { - const wrapper = mount( - <Provider store={store}> - <svg> - <Bar {...mockParam} isSwitching={true} /> - </svg> - </Provider> - ) - expect(wrapper.getElement()).toMatchSnapshot() - }) - - it('should correctly render Bar with isDuel', () => { - const wrapper = mount( - <Provider store={store}> - <svg> - <Bar {...mockParam} isDuel={true} /> - </svg> - </Provider> - ) - expect(wrapper.getElement()).toMatchSnapshot() - }) - - it('should dispatch selected date when bar is clicked', () => { - const wrapper = mount( - <Provider store={store}> - <svg> - <Bar {...mockParam} /> - </svg> - </Provider> - ) - wrapper - .find('rect') - .first() - .simulate('click') - expect(setSelectedDateSpy).toBeCalledTimes(1) - expect(setSelectedDateSpy).toHaveBeenCalledWith( - graphData.actualData[0].date - ) - }) -}) +import React from 'react' +import { mount } from 'enzyme' +import { Provider } from 'react-redux' +import * as reactRedux from 'react-redux' +import { + createMockStore, + mockInitialEcolyoState, +} from '../../../tests/__mocks__/store' +import * as chartActions from 'store/chart/chart.actions' +import Bar from './Bar' +import { FluidType } from 'enum/fluid.enum' +import { TimeStep } from 'enum/timeStep.enum' +import { graphData } from '../../../tests/__mocks__/datachartData.mock' +import { DateTime } from 'luxon' +import { scaleBand, ScaleBand, scaleLinear } from 'd3' + +const mockXScale: ScaleBand<string> = scaleBand() + .domain( + graphData.actualData.map(d => + d.date.toLocaleString(DateTime.DATETIME_SHORT) + ) + ) + .range([0, 10]) + .padding(0.2) + +const mockParam = { + index: 4, + dataload: graphData.actualData[0], + compareDataload: graphData.actualData[1], + fluidType: FluidType.MULTIFLUID, + timeStep: TimeStep.DAY, + showCompare: false, + xScale: mockXScale, + yScale: scaleLinear(), + height: 20, + isSwitching: false, + isDuel: false, +} + +const useSelectorSpy = jest.spyOn(reactRedux, 'useSelector') +const useDispatchSpy = jest.spyOn(reactRedux, 'useDispatch') +const setSelectedDateSpy = jest.spyOn(chartActions, 'setSelectedDate') +const setCurrentDatachartIndexSpy = jest.spyOn( + chartActions, + 'setCurrentDatachartIndex' +) + +describe('Bar component test', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let store: any + beforeEach(() => { + store = createMockStore(mockInitialEcolyoState) + useDispatchSpy.mockClear() + setSelectedDateSpy.mockClear() + setCurrentDatachartIndexSpy.mockClear() + }) + + useSelectorSpy.mockReturnValue({ + selectedDate: DateTime.fromISO('2020-10-01T00:00:00.000Z', { + zone: 'utc', + }), + }) + + it('should correctly render Multifluid Bar', () => { + const wrapper = mount( + <Provider store={store}> + <svg> + <Bar {...mockParam} /> + </svg> + </Provider> + ) + expect(wrapper.getElement()).toMatchSnapshot() + }) + + it('should correctly render Electricity Bar', () => { + const wrapper = mount( + <Provider store={store}> + <svg> + <Bar {...mockParam} fluidType={FluidType.ELECTRICITY} /> + </svg> + </Provider> + ) + expect(wrapper.getElement()).toMatchSnapshot() + }) + + it('should correctly render Water Bar', () => { + const wrapper = mount( + <Provider store={store}> + <svg> + <Bar {...mockParam} fluidType={FluidType.WATER} /> + </svg> + </Provider> + ) + expect(wrapper.getElement()).toMatchSnapshot() + }) + + it('should correctly render Gas Bar', () => { + const wrapper = mount( + <Provider store={store}> + <svg> + <Bar {...mockParam} fluidType={FluidType.GAS} /> + </svg> + </Provider> + ) + expect(wrapper.getElement()).toMatchSnapshot() + }) + + it('should correctly render Bar with showCompare', () => { + const wrapper = mount( + <Provider store={store}> + <svg> + <Bar {...mockParam} showCompare={true} /> + </svg> + </Provider> + ) + expect(wrapper.getElement()).toMatchSnapshot() + }) + + it('should correctly render Bar with isSwitching', () => { + const wrapper = mount( + <Provider store={store}> + <svg> + <Bar {...mockParam} isSwitching={true} /> + </svg> + </Provider> + ) + expect(wrapper.getElement()).toMatchSnapshot() + }) + + it('should correctly render Bar with isDuel', () => { + const wrapper = mount( + <Provider store={store}> + <svg> + <Bar {...mockParam} isDuel={true} /> + </svg> + </Provider> + ) + expect(wrapper.getElement()).toMatchSnapshot() + }) + + it('should dispatch selected date when bar is clicked', () => { + const wrapper = mount( + <Provider store={store}> + <svg> + <Bar {...mockParam} /> + </svg> + </Provider> + ) + wrapper + .find('rect') + .first() + .simulate('click') + expect(setSelectedDateSpy).toBeCalledTimes(1) + expect(setSelectedDateSpy).toHaveBeenCalledWith( + graphData.actualData[0].date + ) + }) +}) diff --git a/src/components/Connection/ConnectionForm.spec.tsx b/src/components/Connection/ConnectionForm.spec.tsx index feaaf56b08667e728dba2c46cfa902d719d7480f..56a041315645e2ccee4dfe086b0fdfec5ae1be72 100644 --- a/src/components/Connection/ConnectionForm.spec.tsx +++ b/src/components/Connection/ConnectionForm.spec.tsx @@ -1,41 +1,41 @@ -import React from 'react' -import { mount } from 'enzyme' -import ConnectionForm from './ConnectionForm' -import { fluidStatusConnectedData } from '../../../test/__mocks__/fluidStatusData.mock' - -jest.mock('./OAuthForm.tsx', () => { - return jest.fn(() => { - return <></> - }) -}) - -jest.mock('cozy-ui/transpiled/react/I18n', () => { - return { - useI18n: jest.fn(() => { - return { - t: (str: string) => str, - } - }), - } -}) - -const mockDispatch = jest.fn() -jest.mock('react-redux', () => ({ - useDispatch: () => mockDispatch, -})) - -describe('ConnectionForm component test', () => { - it('should call ConnectionOAuthForm', () => { - const wrapper = mount( - <ConnectionForm fluidStatus={fluidStatusConnectedData[2]} /> - ) - expect(wrapper.getElement()).toMatchSnapshot() - }) - - it('should call ConnectionLoginForm', () => { - const wrapper = mount( - <ConnectionForm fluidStatus={fluidStatusConnectedData[0]} /> - ) - expect(wrapper.getElement()).toMatchSnapshot() - }) -}) +import React from 'react' +import { mount } from 'enzyme' +import ConnectionForm from './ConnectionForm' +import { fluidStatusConnectedData } from '../../../tests/__mocks__/fluidStatusData.mock' + +jest.mock('./OAuthForm.tsx', () => { + return jest.fn(() => { + return <></> + }) +}) + +jest.mock('cozy-ui/transpiled/react/I18n', () => { + return { + useI18n: jest.fn(() => { + return { + t: (str: string) => str, + } + }), + } +}) + +const mockDispatch = jest.fn() +jest.mock('react-redux', () => ({ + useDispatch: () => mockDispatch, +})) + +describe('ConnectionForm component test', () => { + it('should call ConnectionOAuthForm', () => { + const wrapper = mount( + <ConnectionForm fluidStatus={fluidStatusConnectedData[2]} /> + ) + expect(wrapper.getElement()).toMatchSnapshot() + }) + + it('should call ConnectionLoginForm', () => { + const wrapper = mount( + <ConnectionForm fluidStatus={fluidStatusConnectedData[0]} /> + ) + expect(wrapper.getElement()).toMatchSnapshot() + }) +}) diff --git a/src/components/Duel/DuelOngoing.spec.tsx b/src/components/Duel/DuelOngoing.spec.tsx index 05a75952ed6d85c6cac4c2947ca8e9db6c687fb3..e99ab78e51d1545827cfc0996ae3057b4b551a5f 100644 --- a/src/components/Duel/DuelOngoing.spec.tsx +++ b/src/components/Duel/DuelOngoing.spec.tsx @@ -1,108 +1,108 @@ -import React from 'react' -import { mount } from 'enzyme' -import { Provider } from 'react-redux' -import { act } from '@testing-library/react' -import configureStore from 'redux-mock-store' -import DuelOngoing from 'components/Duel/DuelOngoing' -import { UserChallenge } from 'models' -import { DateTime } from 'luxon' -import { UserChallengeState } from 'enum/userChallenge.enum' -import { globalStateData } from '../../../test/__mocks__/globalStateData.mock' -import { userChallengeData } from '../../../test/__mocks__/userChallengeData.mock' -import { challengeStateData } from '../../../test/__mocks__/challengeStateData.mock' -import DuelResultModal from './DuelResultModal' - -jest.mock('cozy-ui/transpiled/react/I18n', () => { - return { - useI18n: jest.fn(() => { - return { - t: (str: string) => str, - } - }), - } -}) - -const mockUserChallengeUpdateFlag = jest.fn() -const mockIsChallengeDone = jest.fn() -jest.mock('services/challenge.service', () => { - return jest.fn(() => { - return { - updateUserChallenge: mockUserChallengeUpdateFlag, - isChallengeDone: mockIsChallengeDone, - } - }) -}) - -const mockHistoryPush = jest.fn() -jest.mock('react-router-dom', () => ({ - ...jest.requireActual('react-router-dom'), - useHistory: () => ({ - push: mockHistoryPush, - }), -})) - -jest.mock('components/Duel/DuelChart', () => 'mock-duelchart') - -const mockStore = configureStore([]) - -describe('DuelOngoing component', () => { - it('should be rendered correctly', async () => { - const store = mockStore({ - ecolyo: { - global: globalStateData, - challenge: challengeStateData, - }, - }) - mockIsChallengeDone.mockResolvedValue({ - isDone: false, - isWin: false, - isEmpty: false, - }) - const wrapper = mount( - <Provider store={store}> - <DuelOngoing userChallenge={userChallengeData[0]} /> - </Provider> - ) - await act(async () => { - await new Promise(resolve => setTimeout(resolve)) - wrapper.update() - }) - expect(wrapper.find('.duel-title').text()).toEqual( - userChallengeData[1].duel.title - ) - expect(wrapper.find('.duel-goal').exists()).toBeTruthy() - expect(wrapper.find('.duel-consumption').exists()).toBeTruthy() - expect(wrapper.find('.duel-chart').exists()).toBeTruthy() - expect(wrapper.find('.caption-icon').exists()).toBeTruthy() - }) - - it('should display the result Modal when duel is done', async () => { - const store = mockStore({ - ecolyo: { - global: globalStateData, - challenge: challengeStateData, - }, - }) - const updatedUserChallenge: UserChallenge = { - ...userChallengeData[0], - state: UserChallengeState.DUEL, - startDate: DateTime.local().setZone('utc', { keepLocalTime: true }), - } - mockIsChallengeDone.mockResolvedValue({ - isDone: true, - isWin: true, - isEmpty: false, - }) - mockUserChallengeUpdateFlag.mockResolvedValue(updatedUserChallenge) - const wrapper = mount( - <Provider store={store}> - <DuelOngoing userChallenge={updatedUserChallenge} /> - </Provider> - ) - await act(async () => { - await new Promise(resolve => setTimeout(resolve)) - wrapper.update() - }) - expect(wrapper.find(DuelResultModal).exists()).toBeTruthy() - }) -}) +import React from 'react' +import { mount } from 'enzyme' +import { Provider } from 'react-redux' +import { act } from '@testing-library/react' +import configureStore from 'redux-mock-store' +import DuelOngoing from 'components/Duel/DuelOngoing' +import { UserChallenge } from 'models' +import { DateTime } from 'luxon' +import { UserChallengeState } from 'enum/userChallenge.enum' +import { globalStateData } from '../../../tests/__mocks__/globalStateData.mock' +import { userChallengeData } from '../../../tests/__mocks__/userChallengeData.mock' +import { challengeStateData } from '../../../tests/__mocks__/challengeStateData.mock' +import DuelResultModal from './DuelResultModal' + +jest.mock('cozy-ui/transpiled/react/I18n', () => { + return { + useI18n: jest.fn(() => { + return { + t: (str: string) => str, + } + }), + } +}) + +const mockUserChallengeUpdateFlag = jest.fn() +const mockIsChallengeDone = jest.fn() +jest.mock('services/challenge.service', () => { + return jest.fn(() => { + return { + updateUserChallenge: mockUserChallengeUpdateFlag, + isChallengeDone: mockIsChallengeDone, + } + }) +}) + +const mockHistoryPush = jest.fn() +jest.mock('react-router-dom', () => ({ + ...jest.requireActual('react-router-dom'), + useHistory: () => ({ + push: mockHistoryPush, + }), +})) + +jest.mock('components/Duel/DuelChart', () => 'mock-duelchart') + +const mockStore = configureStore([]) + +describe('DuelOngoing component', () => { + it('should be rendered correctly', async () => { + const store = mockStore({ + ecolyo: { + global: globalStateData, + challenge: challengeStateData, + }, + }) + mockIsChallengeDone.mockResolvedValue({ + isDone: false, + isWin: false, + isEmpty: false, + }) + const wrapper = mount( + <Provider store={store}> + <DuelOngoing userChallenge={userChallengeData[0]} /> + </Provider> + ) + await act(async () => { + await new Promise(resolve => setTimeout(resolve)) + wrapper.update() + }) + expect(wrapper.find('.duel-title').text()).toEqual( + userChallengeData[1].duel.title + ) + expect(wrapper.find('.duel-goal').exists()).toBeTruthy() + expect(wrapper.find('.duel-consumption').exists()).toBeTruthy() + expect(wrapper.find('.duel-chart').exists()).toBeTruthy() + expect(wrapper.find('.caption-icon').exists()).toBeTruthy() + }) + + it('should display the result Modal when duel is done', async () => { + const store = mockStore({ + ecolyo: { + global: globalStateData, + challenge: challengeStateData, + }, + }) + const updatedUserChallenge: UserChallenge = { + ...userChallengeData[0], + state: UserChallengeState.DUEL, + startDate: DateTime.local().setZone('utc', { keepLocalTime: true }), + } + mockIsChallengeDone.mockResolvedValue({ + isDone: true, + isWin: true, + isEmpty: false, + }) + mockUserChallengeUpdateFlag.mockResolvedValue(updatedUserChallenge) + const wrapper = mount( + <Provider store={store}> + <DuelOngoing userChallenge={updatedUserChallenge} /> + </Provider> + ) + await act(async () => { + await new Promise(resolve => setTimeout(resolve)) + wrapper.update() + }) + expect(wrapper.find(DuelResultModal).exists()).toBeTruthy() + }) +}) diff --git a/src/components/Duel/DuelUnlocked.spec.tsx b/src/components/Duel/DuelUnlocked.spec.tsx index b4bf9f008452d5d2acb1ea6c4ea0eba4de4e0174..81269d0baaa114ae793c70ccaf923c1d0ae60b69 100644 --- a/src/components/Duel/DuelUnlocked.spec.tsx +++ b/src/components/Duel/DuelUnlocked.spec.tsx @@ -1,89 +1,89 @@ -import React from 'react' -import { mount } from 'enzyme' -import { Provider } from 'react-redux' -import configureStore from 'redux-mock-store' -import DuelUnlocked from 'components/Duel/DuelUnlocked' -import { globalStateData } from '../../../test/__mocks__/globalStateData.mock' -import { userChallengeData } from '../../../test/__mocks__/userChallengeData.mock' -import { formatNumberValues } from 'utils/utils' -import MuiButton from '@material-ui/core/Button' -import StyledIcon from 'components/CommonKit/Icon/StyledIcon' -import { FluidType } from 'enum/fluid.enum' -import { UserChallengeUpdateFlag } from 'enum/userChallenge.enum' - -jest.mock('cozy-ui/transpiled/react/I18n', () => { - return { - useI18n: jest.fn(() => { - return { - t: (str: string) => str, - } - }), - } -}) - -const mockUserChallengeUpdateFlag = jest.fn() -const mockGetUserChallengeDataload = jest.fn() -jest.mock('services/challenge.service', () => { - return jest.fn(() => { - return { - updateUserChallenge: mockUserChallengeUpdateFlag, - getUserChallengeDataload: mockGetUserChallengeDataload, - } - }) -}) - -const mockStore = configureStore([]) - -describe('DuelUnlocked component', () => { - it('should be rendered correctly', () => { - const store = mockStore({ - ecolyo: { - global: globalStateData, - }, - }) - const average: string = formatNumberValues( - userChallengeData[1].duel.threshold - ).toString() - const description: string = - '"' + - userChallengeData[1].duel.description.replace('#CONSUMPTION', average) + - '"' - const wrapper = mount( - <Provider store={store}> - <DuelUnlocked userChallenge={userChallengeData[0]} /> - </Provider> - ) - expect(wrapper.find('.duel-title').text()).toEqual( - userChallengeData[1].duel.title - ) - expect(wrapper.find(StyledIcon).exists()).toBeTruthy() - expect(wrapper.find('.duel-description').text()).toEqual(description) - expect(wrapper.find('.duel-average-info').exists()).toBeTruthy() - expect(wrapper.find('.button-start').exists()).toBeTruthy() - }) - - it('should update userChallenge when launching duel with configured fluid', () => { - const updateGlobalStoreData = { - ...globalStateData, - fluidTypes: [FluidType.ELECTRICITY], - } - const store = mockStore({ - ecolyo: { - global: updateGlobalStoreData, - }, - }) - const wrapper = mount( - <Provider store={store}> - <DuelUnlocked userChallenge={userChallengeData[0]} /> - </Provider> - ) - wrapper - .find('.button-start') - .find(MuiButton) - .simulate('click') - expect(mockUserChallengeUpdateFlag).toHaveBeenCalledWith( - userChallengeData[0], - UserChallengeUpdateFlag.DUEL_START - ) - }) -}) +import React from 'react' +import { mount } from 'enzyme' +import { Provider } from 'react-redux' +import configureStore from 'redux-mock-store' +import DuelUnlocked from 'components/Duel/DuelUnlocked' +import { globalStateData } from '../../../tests/__mocks__/globalStateData.mock' +import { userChallengeData } from '../../../tests/__mocks__/userChallengeData.mock' +import { formatNumberValues } from 'utils/utils' +import MuiButton from '@material-ui/core/Button' +import StyledIcon from 'components/CommonKit/Icon/StyledIcon' +import { FluidType } from 'enum/fluid.enum' +import { UserChallengeUpdateFlag } from 'enum/userChallenge.enum' + +jest.mock('cozy-ui/transpiled/react/I18n', () => { + return { + useI18n: jest.fn(() => { + return { + t: (str: string) => str, + } + }), + } +}) + +const mockUserChallengeUpdateFlag = jest.fn() +const mockGetUserChallengeDataload = jest.fn() +jest.mock('services/challenge.service', () => { + return jest.fn(() => { + return { + updateUserChallenge: mockUserChallengeUpdateFlag, + getUserChallengeDataload: mockGetUserChallengeDataload, + } + }) +}) + +const mockStore = configureStore([]) + +describe('DuelUnlocked component', () => { + it('should be rendered correctly', () => { + const store = mockStore({ + ecolyo: { + global: globalStateData, + }, + }) + const average: string = formatNumberValues( + userChallengeData[1].duel.threshold + ).toString() + const description: string = + '"' + + userChallengeData[1].duel.description.replace('#CONSUMPTION', average) + + '"' + const wrapper = mount( + <Provider store={store}> + <DuelUnlocked userChallenge={userChallengeData[0]} /> + </Provider> + ) + expect(wrapper.find('.duel-title').text()).toEqual( + userChallengeData[1].duel.title + ) + expect(wrapper.find(StyledIcon).exists()).toBeTruthy() + expect(wrapper.find('.duel-description').text()).toEqual(description) + expect(wrapper.find('.duel-average-info').exists()).toBeTruthy() + expect(wrapper.find('.button-start').exists()).toBeTruthy() + }) + + it('should update userChallenge when launching duel with configured fluid', () => { + const updateGlobalStoreData = { + ...globalStateData, + fluidTypes: [FluidType.ELECTRICITY], + } + const store = mockStore({ + ecolyo: { + global: updateGlobalStoreData, + }, + }) + const wrapper = mount( + <Provider store={store}> + <DuelUnlocked userChallenge={userChallengeData[0]} /> + </Provider> + ) + wrapper + .find('.button-start') + .find(MuiButton) + .simulate('click') + expect(mockUserChallengeUpdateFlag).toHaveBeenCalledWith( + userChallengeData[0], + UserChallengeUpdateFlag.DUEL_START + ) + }) +}) diff --git a/src/components/Duel/DuelView.spec.tsx b/src/components/Duel/DuelView.spec.tsx index 8bfbfca09281fd632ada8ea3940da5053e8dc114..5d6eece3cf01f26b9ecca538b2eec92301fc5c1f 100644 --- a/src/components/Duel/DuelView.spec.tsx +++ b/src/components/Duel/DuelView.spec.tsx @@ -1,95 +1,95 @@ -import React from 'react' -import { shallow } from 'enzyme' -import * as reactRedux from 'react-redux' -import DuelView from 'components/Duel/DuelView' -import { UserChallengeState } from 'enum/userChallenge.enum' -import { challengeStateData } from '../../../test/__mocks__/challengeStateData.mock' -import { userChallengeData } from '../../../test/__mocks__/userChallengeData.mock' -import DuelError from './DuelError' -import DuelUnlocked from './DuelUnlocked' -import DuelOngoing from './DuelOngoing' -import { UserDuelState } from 'enum/userDuel.enum' - -const mockUseSelector = jest.spyOn(reactRedux, 'useSelector') - -describe('DuelView component', () => { - it('should be rendered with DuelError component when no current challenge', () => { - mockUseSelector.mockReturnValue(challengeStateData) - const wrapper = shallow(<DuelView />) - expect(wrapper.find(DuelError).exists()).toBeTruthy() - }) - - it('should be rendered with DuelError component when current challenge with state = duel and duel state = done', () => { - const updatedUserChallenge = { - ...userChallengeData[1], - state: UserChallengeState.DUEL, - duel: { ...userChallengeData[1].duel, state: UserDuelState.DONE }, - } - const updatedChallengeState = { - ...challengeStateData, - currentChallenge: updatedUserChallenge, - } - mockUseSelector.mockReturnValue(updatedChallengeState) - const wrapper = shallow(<DuelView />) - expect(wrapper.find(DuelError).exists()).toBeTruthy() - }) - - it('should be rendered with DuelError component when current challenge with state = duel and duel state = locked', () => { - const updatedUserChallenge = { - ...userChallengeData[1], - state: UserChallengeState.DUEL, - duel: { ...userChallengeData[1].duel, state: UserDuelState.LOCKED }, - } - const updatedChallengeState = { - ...challengeStateData, - currentChallenge: updatedUserChallenge, - } - mockUseSelector.mockReturnValue(updatedChallengeState) - const wrapper = shallow(<DuelView />) - expect(wrapper.find(DuelError).exists()).toBeTruthy() - }) - - it('should be rendered with DuelError component when current challenge with state != duel ', () => { - const updatedUserChallenge = { - ...userChallengeData[1], - state: UserChallengeState.ONGOING, - } - const updatedChallengeState = { - ...challengeStateData, - currentChallenge: updatedUserChallenge, - } - mockUseSelector.mockReturnValue(updatedChallengeState) - const wrapper = shallow(<DuelView />) - expect(wrapper.find(DuelError).exists()).toBeTruthy() - }) - - it('should be rendered with DuelUnlocked component when current challenge with state = duel and duel state = unlocked', () => { - const updatedUserChallenge = { - ...userChallengeData[1], - state: UserChallengeState.DUEL, - duel: { ...userChallengeData[1].duel, state: UserDuelState.UNLOCKED }, - } - const updatedChallengeState = { - ...challengeStateData, - currentChallenge: updatedUserChallenge, - } - mockUseSelector.mockReturnValue(updatedChallengeState) - const wrapper = shallow(<DuelView />) - expect(wrapper.find(DuelUnlocked).exists()).toBeTruthy() - }) - - it('should be rendered with DuelOngoing component when current challenge with state = duel and duel state = ongoing', () => { - const updatedUserChallenge = { - ...userChallengeData[1], - state: UserChallengeState.DUEL, - duel: { ...userChallengeData[1].duel, state: UserDuelState.ONGOING }, - } - const updatedChallengeState = { - ...challengeStateData, - currentChallenge: updatedUserChallenge, - } - mockUseSelector.mockReturnValue(updatedChallengeState) - const wrapper = shallow(<DuelView />) - expect(wrapper.find(DuelOngoing).exists()).toBeTruthy() - }) -}) +import React from 'react' +import { shallow } from 'enzyme' +import * as reactRedux from 'react-redux' +import DuelView from 'components/Duel/DuelView' +import { UserChallengeState } from 'enum/userChallenge.enum' +import { challengeStateData } from '../../../tests/__mocks__/challengeStateData.mock' +import { userChallengeData } from '../../../tests/__mocks__/userChallengeData.mock' +import DuelError from './DuelError' +import DuelUnlocked from './DuelUnlocked' +import DuelOngoing from './DuelOngoing' +import { UserDuelState } from 'enum/userDuel.enum' + +const mockUseSelector = jest.spyOn(reactRedux, 'useSelector') + +describe('DuelView component', () => { + it('should be rendered with DuelError component when no current challenge', () => { + mockUseSelector.mockReturnValue(challengeStateData) + const wrapper = shallow(<DuelView />) + expect(wrapper.find(DuelError).exists()).toBeTruthy() + }) + + it('should be rendered with DuelError component when current challenge with state = duel and duel state = done', () => { + const updatedUserChallenge = { + ...userChallengeData[1], + state: UserChallengeState.DUEL, + duel: { ...userChallengeData[1].duel, state: UserDuelState.DONE }, + } + const updatedChallengeState = { + ...challengeStateData, + currentChallenge: updatedUserChallenge, + } + mockUseSelector.mockReturnValue(updatedChallengeState) + const wrapper = shallow(<DuelView />) + expect(wrapper.find(DuelError).exists()).toBeTruthy() + }) + + it('should be rendered with DuelError component when current challenge with state = duel and duel state = locked', () => { + const updatedUserChallenge = { + ...userChallengeData[1], + state: UserChallengeState.DUEL, + duel: { ...userChallengeData[1].duel, state: UserDuelState.LOCKED }, + } + const updatedChallengeState = { + ...challengeStateData, + currentChallenge: updatedUserChallenge, + } + mockUseSelector.mockReturnValue(updatedChallengeState) + const wrapper = shallow(<DuelView />) + expect(wrapper.find(DuelError).exists()).toBeTruthy() + }) + + it('should be rendered with DuelError component when current challenge with state != duel ', () => { + const updatedUserChallenge = { + ...userChallengeData[1], + state: UserChallengeState.ONGOING, + } + const updatedChallengeState = { + ...challengeStateData, + currentChallenge: updatedUserChallenge, + } + mockUseSelector.mockReturnValue(updatedChallengeState) + const wrapper = shallow(<DuelView />) + expect(wrapper.find(DuelError).exists()).toBeTruthy() + }) + + it('should be rendered with DuelUnlocked component when current challenge with state = duel and duel state = unlocked', () => { + const updatedUserChallenge = { + ...userChallengeData[1], + state: UserChallengeState.DUEL, + duel: { ...userChallengeData[1].duel, state: UserDuelState.UNLOCKED }, + } + const updatedChallengeState = { + ...challengeStateData, + currentChallenge: updatedUserChallenge, + } + mockUseSelector.mockReturnValue(updatedChallengeState) + const wrapper = shallow(<DuelView />) + expect(wrapper.find(DuelUnlocked).exists()).toBeTruthy() + }) + + it('should be rendered with DuelOngoing component when current challenge with state = duel and duel state = ongoing', () => { + const updatedUserChallenge = { + ...userChallengeData[1], + state: UserChallengeState.DUEL, + duel: { ...userChallengeData[1].duel, state: UserDuelState.ONGOING }, + } + const updatedChallengeState = { + ...challengeStateData, + currentChallenge: updatedUserChallenge, + } + mockUseSelector.mockReturnValue(updatedChallengeState) + const wrapper = shallow(<DuelView />) + expect(wrapper.find(DuelOngoing).exists()).toBeTruthy() + }) +}) diff --git a/src/components/Ecogesture/EcogestureCard.spec.tsx b/src/components/Ecogesture/EcogestureCard.spec.tsx index 51726ea344138dbbb1b1297a981747898684d58b..126950ab5852fbdd14f621b7d6ec59686d1c9dc5 100644 --- a/src/components/Ecogesture/EcogestureCard.spec.tsx +++ b/src/components/Ecogesture/EcogestureCard.spec.tsx @@ -1,23 +1,23 @@ -import React from 'react' -import { shallow } from 'enzyme' -import EcogestureCard from 'components/Ecogesture/EcogestureCard' -import { ecogesturesData } from '../../../test/__mocks__/ecogesturesData.mock' - -jest.mock('cozy-ui/transpiled/react/I18n', () => { - return { - useI18n: jest.fn(() => { - return { - t: (str: string) => str, - } - }), - } -}) - -describe('EcogestureCard component', () => { - it('should be rendered correctly', () => { - const component = shallow( - <EcogestureCard ecogesture={ecogesturesData[0]} /> - ).getElement - expect(component).toMatchSnapshot() - }) -}) +import React from 'react' +import { shallow } from 'enzyme' +import EcogestureCard from 'components/Ecogesture/EcogestureCard' +import { ecogesturesData } from '../../../tests/__mocks__/ecogesturesData.mock' + +jest.mock('cozy-ui/transpiled/react/I18n', () => { + return { + useI18n: jest.fn(() => { + return { + t: (str: string) => str, + } + }), + } +}) + +describe('EcogestureCard component', () => { + it('should be rendered correctly', () => { + const component = shallow( + <EcogestureCard ecogesture={ecogesturesData[0]} /> + ).getElement + expect(component).toMatchSnapshot() + }) +}) diff --git a/src/components/Ecogesture/EcogestureError.spec.tsx b/src/components/Ecogesture/EcogestureError.spec.tsx index 5a09f10ebe982378ea29deb9a8641058a4fe013e..99cbf65bdd0565f9ae86004c625775269216a37c 100644 --- a/src/components/Ecogesture/EcogestureError.spec.tsx +++ b/src/components/Ecogesture/EcogestureError.spec.tsx @@ -1,60 +1,60 @@ -import React from 'react' -import { mount } from 'enzyme' -import configureStore from 'redux-mock-store' -import { profileData } from '../../../test/__mocks__/profile.mock' -import { globalStateData } from '../../../test/__mocks__/globalStateData.mock' -import { Provider } from 'react-redux' -import MuiButton from '@material-ui/core/Button' -import EcogestureError from './EcogestureError' - -jest.mock('cozy-ui/transpiled/react/I18n', () => { - return { - useI18n: jest.fn(() => { - return { - t: (str: string) => str, - } - }), - } -}) -const mockHistoryPush = jest.fn() -jest.mock('react-router-dom', () => ({ - ...jest.requireActual('react-router-dom'), - useHistory: () => ({ - push: mockHistoryPush, - }), -})) -const mockStore = configureStore([]) - -describe('EcogestureError component', () => { - it('should be rendered correctly', () => { - const store = mockStore({ - ecolyo: { - profile: profileData, - global: globalStateData, - }, - }) - const wrapper = mount( - <Provider store={store}> - <EcogestureError /> - </Provider> - ) - expect(wrapper.find(MuiButton).exists()).toBeTruthy() - }) - it('should redirect to profile type form', () => { - const store = mockStore({ - ecolyo: { - profile: profileData, - global: globalStateData, - }, - }) - const wrapper = mount( - <Provider store={store}> - <EcogestureError /> - </Provider> - ) - wrapper - .find('.btn-highlight') - .first() - .simulate('click') - }) -}) +import React from 'react' +import { mount } from 'enzyme' +import configureStore from 'redux-mock-store' +import { profileData } from '../../../tests/__mocks__/profile.mock' +import { globalStateData } from '../../../tests/__mocks__/globalStateData.mock' +import { Provider } from 'react-redux' +import MuiButton from '@material-ui/core/Button' +import EcogestureError from './EcogestureError' + +jest.mock('cozy-ui/transpiled/react/I18n', () => { + return { + useI18n: jest.fn(() => { + return { + t: (str: string) => str, + } + }), + } +}) +const mockHistoryPush = jest.fn() +jest.mock('react-router-dom', () => ({ + ...jest.requireActual('react-router-dom'), + useHistory: () => ({ + push: mockHistoryPush, + }), +})) +const mockStore = configureStore([]) + +describe('EcogestureError component', () => { + it('should be rendered correctly', () => { + const store = mockStore({ + ecolyo: { + profile: profileData, + global: globalStateData, + }, + }) + const wrapper = mount( + <Provider store={store}> + <EcogestureError /> + </Provider> + ) + expect(wrapper.find(MuiButton).exists()).toBeTruthy() + }) + it('should redirect to profile type form', () => { + const store = mockStore({ + ecolyo: { + profile: profileData, + global: globalStateData, + }, + }) + const wrapper = mount( + <Provider store={store}> + <EcogestureError /> + </Provider> + ) + wrapper + .find('.btn-highlight') + .first() + .simulate('click') + }) +}) diff --git a/src/components/Ecogesture/EcogestureModal.spec.tsx b/src/components/Ecogesture/EcogestureModal.spec.tsx index 9566235baaae8bb1843ff196986c97a37a2e6311..b0fbc7280cf463b2a7a78a9199b9a4d3a9ad1826 100644 --- a/src/components/Ecogesture/EcogestureModal.spec.tsx +++ b/src/components/Ecogesture/EcogestureModal.spec.tsx @@ -1,43 +1,43 @@ -import React from 'react' -import { mount } from 'enzyme' -import EcogestureModal from 'components/Ecogesture/EcogestureModal' -import { ecogesturesData } from '../../../test/__mocks__/ecogesturesData.mock' -import configureStore from 'redux-mock-store' -import { globalStateData } from '../../../test/__mocks__/globalStateData.mock' -import { challengeStateData } from '../../../test/__mocks__/challengeStateData.mock' -import { Provider } from 'react-redux' - -jest.mock('cozy-ui/transpiled/react/I18n', () => { - return { - useI18n: jest.fn(() => { - return { - t: (str: string) => str, - } - }), - } -}) - -const mockStore = configureStore([]) - -describe('EcogestureModal component', () => { - it('should be rendered correctly', () => { - const store = mockStore({ - ecolyo: { - global: globalStateData, - challenge: challengeStateData, - }, - }) - const wrapper = mount( - <Provider store={store}> - <EcogestureModal - ecogesture={ecogesturesData[0]} - isAction={false} - handleCloseClick={jest.fn()} - /> - </Provider> - ) - expect(wrapper.find('.em-title').text()).toEqual( - ecogesturesData[0].shortName - ) - }) -}) +import React from 'react' +import { mount } from 'enzyme' +import EcogestureModal from 'components/Ecogesture/EcogestureModal' +import { ecogesturesData } from '../../../tests/__mocks__/ecogesturesData.mock' +import configureStore from 'redux-mock-store' +import { globalStateData } from '../../../tests/__mocks__/globalStateData.mock' +import { challengeStateData } from '../../../tests/__mocks__/challengeStateData.mock' +import { Provider } from 'react-redux' + +jest.mock('cozy-ui/transpiled/react/I18n', () => { + return { + useI18n: jest.fn(() => { + return { + t: (str: string) => str, + } + }), + } +}) + +const mockStore = configureStore([]) + +describe('EcogestureModal component', () => { + it('should be rendered correctly', () => { + const store = mockStore({ + ecolyo: { + global: globalStateData, + challenge: challengeStateData, + }, + }) + const wrapper = mount( + <Provider store={store}> + <EcogestureModal + ecogesture={ecogesturesData[0]} + isAction={false} + handleCloseClick={jest.fn()} + /> + </Provider> + ) + expect(wrapper.find('.em-title').text()).toEqual( + ecogesturesData[0].shortName + ) + }) +}) diff --git a/src/components/Ecogesture/EcogestureView.spec.tsx b/src/components/Ecogesture/EcogestureView.spec.tsx index ac23e6a624766a593645ff88214f7fda73700079..baba729c0016026591b381f015cc15346ead7e1f 100644 --- a/src/components/Ecogesture/EcogestureView.spec.tsx +++ b/src/components/Ecogesture/EcogestureView.spec.tsx @@ -1,70 +1,70 @@ -/* eslint-disable react/display-name */ -import React from 'react' -import { mount } from 'enzyme' -import { Provider } from 'react-redux' -import * as reactRedux from 'react-redux' -import { - createMockStore, - mockInitialEcolyoState, -} from '../../../test/__mocks__/store' -import EcogestureView from 'components/Ecogesture/EcogestureView' -import { Tab } from '@material-ui/core' - -jest.mock('cozy-ui/transpiled/react/I18n', () => { - return { - useI18n: jest.fn(() => { - return { - t: (str: string) => str, - } - }), - } -}) - -jest.mock('components/Header/CozyBar', () => () => <div id="cozybar"></div>) -jest.mock('components/Ecogesture/EcogestureList', () => () => ( - <div id="ecogesturelist"></div> -)) -jest.mock('components/Ecogesture/EcogestureError', () => () => ( - <div id="ecogestureerror"></div> -)) - -const useSelectorSpy = jest.spyOn(reactRedux, 'useSelector') - -describe('EcogestureView component', () => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let store: any - beforeEach(() => { - store = createMockStore(mockInitialEcolyoState) - }) - - it('should be rendered correctly', () => { - useSelectorSpy.mockReturnValue({ - ...mockInitialEcolyoState.profile, - isProfileTypeCompleted: true, - }) - const wrapper = mount( - <Provider store={store}> - <EcogestureView /> - </Provider> - ) - expect(wrapper.find('#cozybar')).toBeTruthy() - expect(wrapper.find(Tab).length).toBe(2) - expect(wrapper.find('#ecogesturelist').length).toBe(2) - }) - - it('should be rendered with EcogestureError', () => { - useSelectorSpy.mockReturnValue({ - ...mockInitialEcolyoState.profile, - isProfileTypeCompleted: false, - }) - const wrapper = mount( - <Provider store={store}> - <EcogestureView /> - </Provider> - ) - expect(wrapper.find('#cozybar')).toBeTruthy() - expect(wrapper.find(Tab).length).toBe(2) - expect(wrapper.find('#ecogesturelist').length).toBe(1) - expect(wrapper.find('#ecogestureerror').length).toBe(1) - }) -}) +/* eslint-disable react/display-name */ +import React from 'react' +import { mount } from 'enzyme' +import { Provider } from 'react-redux' +import * as reactRedux from 'react-redux' +import { + createMockStore, + mockInitialEcolyoState, +} from '../../../tests/__mocks__/store' +import EcogestureView from 'components/Ecogesture/EcogestureView' +import { Tab } from '@material-ui/core' + +jest.mock('cozy-ui/transpiled/react/I18n', () => { + return { + useI18n: jest.fn(() => { + return { + t: (str: string) => str, + } + }), + } +}) + +jest.mock('components/Header/CozyBar', () => () => <div id="cozybar"></div>) +jest.mock('components/Ecogesture/EcogestureList', () => () => ( + <div id="ecogesturelist"></div> +)) +jest.mock('components/Ecogesture/EcogestureError', () => () => ( + <div id="ecogestureerror"></div> +)) + +const useSelectorSpy = jest.spyOn(reactRedux, 'useSelector') + +describe('EcogestureView component', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let store: any + beforeEach(() => { + store = createMockStore(mockInitialEcolyoState) + }) + + it('should be rendered correctly', () => { + useSelectorSpy.mockReturnValue({ + ...mockInitialEcolyoState.profile, + isProfileTypeCompleted: true, + }) + const wrapper = mount( + <Provider store={store}> + <EcogestureView /> + </Provider> + ) + expect(wrapper.find('#cozybar')).toBeTruthy() + expect(wrapper.find(Tab).length).toBe(2) + expect(wrapper.find('#ecogesturelist').length).toBe(2) + }) + + it('should be rendered with EcogestureError', () => { + useSelectorSpy.mockReturnValue({ + ...mockInitialEcolyoState.profile, + isProfileTypeCompleted: false, + }) + const wrapper = mount( + <Provider store={store}> + <EcogestureView /> + </Provider> + ) + expect(wrapper.find('#cozybar')).toBeTruthy() + expect(wrapper.find(Tab).length).toBe(2) + expect(wrapper.find('#ecogesturelist').length).toBe(1) + expect(wrapper.find('#ecogestureerror').length).toBe(1) + }) +}) diff --git a/src/components/Exploration/ExplorationFinished.spec.tsx b/src/components/Exploration/ExplorationFinished.spec.tsx index 515169c6b1e4fc91d87ab6181fd8c6228154654c..7b4a2566b8260cc6b946fe821744db9be3f58866 100644 --- a/src/components/Exploration/ExplorationFinished.spec.tsx +++ b/src/components/Exploration/ExplorationFinished.spec.tsx @@ -1,66 +1,66 @@ -import React from 'react' -import { mount } from 'enzyme' -import { Provider } from 'react-redux' -import configureStore from 'redux-mock-store' -import ExplorationFinished from './ExplorationFinished' -import { globalStateData } from '../../../test/__mocks__/globalStateData.mock' -import { userChallengeData } from '../../../test/__mocks__/userChallengeData.mock' -import MuiButton from '@material-ui/core/Button' -import StyledIcon from 'components/CommonKit/Icon/StyledIcon' - -jest.mock('cozy-ui/transpiled/react/I18n', () => { - return { - useI18n: jest.fn(() => { - return { - t: (str: string) => str, - } - }), - } -}) - -const mockHistoryGoBack = jest.fn() -jest.mock('react-router-dom', () => ({ - ...jest.requireActual('react-router-dom'), - useHistory: () => ({ - goBack: mockHistoryGoBack, - }), -})) - -const mockStore = configureStore([]) - -describe('ExplorationFinished', () => { - it('should be rendered correctly', () => { - const store = mockStore({ - ecolyo: { - global: globalStateData, - }, - }) - const wrapper = mount( - <Provider store={store}> - <ExplorationFinished userChallenge={userChallengeData[0]} /> - </Provider> - ) - expect(wrapper.find(StyledIcon).exists()).toBeTruthy() - expect(wrapper.find('.congratulation').exists()).toBeTruthy() - expect(wrapper.find('.exploration-earn').exists()).toBeTruthy() - expect(wrapper.find('.msg-sucess').text()).toEqual( - userChallengeData[0].exploration.message_success - ) - }) - it('should redirect to challenge on click on styledButton', () => { - const store = mockStore({ - ecolyo: { - global: globalStateData, - }, - }) - const wrapper = mount( - <Provider store={store}> - <ExplorationFinished userChallenge={userChallengeData[0]} /> - </Provider> - ) - wrapper - .find(MuiButton) - .first() - .simulate('click') - }) -}) +import React from 'react' +import { mount } from 'enzyme' +import { Provider } from 'react-redux' +import configureStore from 'redux-mock-store' +import ExplorationFinished from './ExplorationFinished' +import { globalStateData } from '../../../tests/__mocks__/globalStateData.mock' +import { userChallengeData } from '../../../tests/__mocks__/userChallengeData.mock' +import MuiButton from '@material-ui/core/Button' +import StyledIcon from 'components/CommonKit/Icon/StyledIcon' + +jest.mock('cozy-ui/transpiled/react/I18n', () => { + return { + useI18n: jest.fn(() => { + return { + t: (str: string) => str, + } + }), + } +}) + +const mockHistoryGoBack = jest.fn() +jest.mock('react-router-dom', () => ({ + ...jest.requireActual('react-router-dom'), + useHistory: () => ({ + goBack: mockHistoryGoBack, + }), +})) + +const mockStore = configureStore([]) + +describe('ExplorationFinished', () => { + it('should be rendered correctly', () => { + const store = mockStore({ + ecolyo: { + global: globalStateData, + }, + }) + const wrapper = mount( + <Provider store={store}> + <ExplorationFinished userChallenge={userChallengeData[0]} /> + </Provider> + ) + expect(wrapper.find(StyledIcon).exists()).toBeTruthy() + expect(wrapper.find('.congratulation').exists()).toBeTruthy() + expect(wrapper.find('.exploration-earn').exists()).toBeTruthy() + expect(wrapper.find('.msg-sucess').text()).toEqual( + userChallengeData[0].exploration.message_success + ) + }) + it('should redirect to challenge on click on styledButton', () => { + const store = mockStore({ + ecolyo: { + global: globalStateData, + }, + }) + const wrapper = mount( + <Provider store={store}> + <ExplorationFinished userChallenge={userChallengeData[0]} /> + </Provider> + ) + wrapper + .find(MuiButton) + .first() + .simulate('click') + }) +}) diff --git a/src/components/Exploration/ExplorationOngoing.spec.tsx b/src/components/Exploration/ExplorationOngoing.spec.tsx index 406f1cc6a722ac5c6628ada7db5320387c04f35b..58298416b24af5ea215c12f0f7c65d583819e51a 100644 --- a/src/components/Exploration/ExplorationOngoing.spec.tsx +++ b/src/components/Exploration/ExplorationOngoing.spec.tsx @@ -3,9 +3,9 @@ import { mount } from 'enzyme' import { Provider } from 'react-redux' import configureStore from 'redux-mock-store' import ExplorationOngoing from 'components/Exploration/ExplorationOngoing' -import { globalStateData } from '../../../test/__mocks__/globalStateData.mock' -import { userChallengeData } from '../../../test/__mocks__/userChallengeData.mock' -import { challengeStateData } from '../../../test/__mocks__/challengeStateData.mock' +import { globalStateData } from '../../../tests/__mocks__/globalStateData.mock' +import { userChallengeData } from '../../../tests/__mocks__/userChallengeData.mock' +import { challengeStateData } from '../../../tests/__mocks__/challengeStateData.mock' jest.mock('cozy-ui/transpiled/react/I18n', () => { return { diff --git a/src/components/Exploration/ExplorationView.spec.tsx b/src/components/Exploration/ExplorationView.spec.tsx index a137d4d58d4c8223f8dbf7266f1eb7cb260ee824..afc90e3104495de4f9e48c1526640ed962d4b717 100644 --- a/src/components/Exploration/ExplorationView.spec.tsx +++ b/src/components/Exploration/ExplorationView.spec.tsx @@ -1,59 +1,59 @@ -import React from 'react' -import { shallow } from 'enzyme' -import * as reactRedux from 'react-redux' -import ExplorationView from './ExplorationView' -import { userChallengeData } from '../../../test/__mocks__/userChallengeData.mock' -import { UserQuizState } from 'enum/userQuiz.enum' -import { challengeStateData } from '../../../test/__mocks__/challengeStateData.mock' -import ExplorationFinished from './ExplorationFinished' -import ExplorationError from './ExplorationError' -import ExplorationOngoing from './ExplorationOngoing' - -const mockUseSelector = jest.spyOn(reactRedux, 'useSelector') - -describe('ExplorationView', () => { - it('should be rendered with ExplorationView component when no exploration state', () => { - mockUseSelector.mockReturnValue(challengeStateData) - const wrapper = shallow(<ExplorationView />) - expect(wrapper.find(ExplorationError).exists()) - }) - it('should be rendered with ExplorationView component when exploration state = unlocked', () => { - const updatedUserChallenge = { - ...userChallengeData[0], - quiz: { ...userChallengeData[0].quiz, state: UserQuizState.UNLOCKED }, - } - const updatedChallengeState = { - ...challengeStateData, - currentChallenge: updatedUserChallenge, - } - mockUseSelector.mockReturnValue(updatedChallengeState) - const wrapper = shallow(<ExplorationView />) - expect(wrapper.find(ExplorationOngoing).exists()) - }) - it('should be rendered with ExplorationView component when exploration state = ongoing', () => { - const updatedUserChallenge = { - ...userChallengeData[0], - quiz: { ...userChallengeData[0].quiz, state: UserQuizState.ONGOING }, - } - const updatedChallengeState = { - ...challengeStateData, - currentChallenge: updatedUserChallenge, - } - mockUseSelector.mockReturnValue(updatedChallengeState) - const wrapper = shallow(<ExplorationView />) - expect(wrapper.find(ExplorationOngoing).exists()) - }) - it('should be rendered with ExplorationView component when exploration state = Done', () => { - const updatedUserChallenge = { - ...userChallengeData[0], - quiz: { ...userChallengeData[0].quiz, state: UserQuizState.DONE }, - } - const updatedChallengeState = { - ...challengeStateData, - currentChallenge: updatedUserChallenge, - } - mockUseSelector.mockReturnValue(updatedChallengeState) - const wrapper = shallow(<ExplorationView />) - expect(wrapper.find(ExplorationFinished).exists()) - }) -}) +import React from 'react' +import { shallow } from 'enzyme' +import * as reactRedux from 'react-redux' +import ExplorationView from './ExplorationView' +import { userChallengeData } from '../../../tests/__mocks__/userChallengeData.mock' +import { UserQuizState } from 'enum/userQuiz.enum' +import { challengeStateData } from '../../../tests/__mocks__/challengeStateData.mock' +import ExplorationFinished from './ExplorationFinished' +import ExplorationError from './ExplorationError' +import ExplorationOngoing from './ExplorationOngoing' + +const mockUseSelector = jest.spyOn(reactRedux, 'useSelector') + +describe('ExplorationView', () => { + it('should be rendered with ExplorationView component when no exploration state', () => { + mockUseSelector.mockReturnValue(challengeStateData) + const wrapper = shallow(<ExplorationView />) + expect(wrapper.find(ExplorationError).exists()) + }) + it('should be rendered with ExplorationView component when exploration state = unlocked', () => { + const updatedUserChallenge = { + ...userChallengeData[0], + quiz: { ...userChallengeData[0].quiz, state: UserQuizState.UNLOCKED }, + } + const updatedChallengeState = { + ...challengeStateData, + currentChallenge: updatedUserChallenge, + } + mockUseSelector.mockReturnValue(updatedChallengeState) + const wrapper = shallow(<ExplorationView />) + expect(wrapper.find(ExplorationOngoing).exists()) + }) + it('should be rendered with ExplorationView component when exploration state = ongoing', () => { + const updatedUserChallenge = { + ...userChallengeData[0], + quiz: { ...userChallengeData[0].quiz, state: UserQuizState.ONGOING }, + } + const updatedChallengeState = { + ...challengeStateData, + currentChallenge: updatedUserChallenge, + } + mockUseSelector.mockReturnValue(updatedChallengeState) + const wrapper = shallow(<ExplorationView />) + expect(wrapper.find(ExplorationOngoing).exists()) + }) + it('should be rendered with ExplorationView component when exploration state = Done', () => { + const updatedUserChallenge = { + ...userChallengeData[0], + quiz: { ...userChallengeData[0].quiz, state: UserQuizState.DONE }, + } + const updatedChallengeState = { + ...challengeStateData, + currentChallenge: updatedUserChallenge, + } + mockUseSelector.mockReturnValue(updatedChallengeState) + const wrapper = shallow(<ExplorationView />) + expect(wrapper.find(ExplorationFinished).exists()) + }) +}) diff --git a/src/components/Feedback/FeedbackModal.spec.tsx b/src/components/Feedback/FeedbackModal.spec.tsx index ea30f79155b7d4fc7252a812415cd772d1188d68..0e970edd6dacc89d47424b2b7294ca12dec826b6 100644 --- a/src/components/Feedback/FeedbackModal.spec.tsx +++ b/src/components/Feedback/FeedbackModal.spec.tsx @@ -1,124 +1,124 @@ -import React from 'react' -import * as reactRedux from 'react-redux' -import { shallow } from 'enzyme' -import FeedbackModal from 'components/Feedback/FeedbackModal' - -import MuiButton from '@material-ui/core/Button' -import Modal from 'components/CommonKit/Modal/Modal' -import StyledIconButton from 'components/CommonKit/IconButton/StyledIconButton' -import { userChallengeExplo1OnGoing } from '../../../test/__mocks__/userChallengeData.mock' - -const mockSendMail = jest.fn() -jest.mock('services/mail.service', () => { - return jest.fn(() => { - return { - SendMail: mockSendMail, - } - }) -}) - -jest.mock('cozy-ui/transpiled/react/I18n', () => { - return { - useI18n: jest.fn(() => { - return { - t: (str: string) => str, - } - }), - } -}) - -const handleFeedbackModalClose = jest.fn() - -const mockUseSelector = jest.spyOn(reactRedux, 'useSelector') -const mockUseDispatch = jest.spyOn(reactRedux, 'useDispatch') - -describe('FeedbackModal component', () => { - it('should render the component', () => { - mockUseDispatch.mockReturnValue(jest.fn()) - mockUseSelector.mockReturnValue(userChallengeExplo1OnGoing) - const component = shallow( - <FeedbackModal handleCloseClick={handleFeedbackModalClose} /> - ).getElement() - expect(component).toMatchSnapshot() - }) -}) -describe('FeedbackModal functionnalities', () => { - it('should should send an email to the support', () => { - mockUseDispatch.mockReturnValue(jest.fn()) - mockUseSelector.mockReturnValue(userChallengeExplo1OnGoing) - - const wrapper = shallow( - <FeedbackModal handleCloseClick={handleFeedbackModalClose} /> - ) - - const mockPlatform = 'platform' - const mockVendor = 'vendor' - const mockUserAgent = 'userAgent' - Object.defineProperty(navigator, 'platform', { value: mockPlatform }) - Object.defineProperty(navigator, 'vendor', { value: mockVendor }) - Object.defineProperty(navigator, 'userAgent', { value: mockUserAgent }) - - const expectedMailData = { - mode: 'from', - to: [{ name: 'Support', email: 'ecolyo@grandlyon.com' }], - subject: '[Ecolyo] - Feedbacks - feedback.type_bug', - parts: [ - { - type: 'text/plain', - body: - 'Type: feedback.type_bug\n' + - '\n' + - 'Description:\n' + - 'La description\n' + - 'Ecolyo\n' + - 'v0.0.0\n' + - '\n' + - 'Location: http://localhost/\n' + - '\n' + - 'Browser:\n' + - 'On null\n' + - 'From null\n' + - 'null\n' + - '\n' + - 'Navigator:' + - `\nOn ${mockPlatform}` + - `\nFrom ${mockVendor}` + - `\n${mockUserAgent}`, - }, - ], - } - - wrapper - .find('div.fb-selector-item') - .first() - .simulate('click') - wrapper - .find('#idFeedbackDescription') - .simulate('change', { target: { value: 'La description' } }) - wrapper.find(MuiButton).simulate('click') - - expect(mockSendMail).toHaveBeenCalledWith( - expect.anything(), - expectedMailData - ) - }) - it('should close the modal and reset the inputs', () => { - mockUseDispatch.mockReturnValue(jest.fn()) - mockUseSelector.mockReturnValue(userChallengeExplo1OnGoing) - const wrapper = shallow( - <FeedbackModal handleCloseClick={handleFeedbackModalClose} /> - ) - wrapper - .find('#idFeedbackDescription') - .simulate('change', { target: { value: 'La description' } }) - wrapper - .find(Modal) - .dive() - .find(StyledIconButton) - .simulate('click') - expect(handleFeedbackModalClose).toHaveBeenCalledTimes(1) - setTimeout(() => { - expect(wrapper.find('#idFeedbackDescription').prop('value')).toBeNull() - }) - }) -}) +import React from 'react' +import * as reactRedux from 'react-redux' +import { shallow } from 'enzyme' +import FeedbackModal from 'components/Feedback/FeedbackModal' + +import MuiButton from '@material-ui/core/Button' +import Modal from 'components/CommonKit/Modal/Modal' +import StyledIconButton from 'components/CommonKit/IconButton/StyledIconButton' +import { userChallengeExplo1OnGoing } from '../../../tests/__mocks__/userChallengeData.mock' + +const mockSendMail = jest.fn() +jest.mock('services/mail.service', () => { + return jest.fn(() => { + return { + SendMail: mockSendMail, + } + }) +}) + +jest.mock('cozy-ui/transpiled/react/I18n', () => { + return { + useI18n: jest.fn(() => { + return { + t: (str: string) => str, + } + }), + } +}) + +const handleFeedbackModalClose = jest.fn() + +const mockUseSelector = jest.spyOn(reactRedux, 'useSelector') +const mockUseDispatch = jest.spyOn(reactRedux, 'useDispatch') + +describe('FeedbackModal component', () => { + it('should render the component', () => { + mockUseDispatch.mockReturnValue(jest.fn()) + mockUseSelector.mockReturnValue(userChallengeExplo1OnGoing) + const component = shallow( + <FeedbackModal handleCloseClick={handleFeedbackModalClose} /> + ).getElement() + expect(component).toMatchSnapshot() + }) +}) +describe('FeedbackModal functionnalities', () => { + it('should should send an email to the support', () => { + mockUseDispatch.mockReturnValue(jest.fn()) + mockUseSelector.mockReturnValue(userChallengeExplo1OnGoing) + + const wrapper = shallow( + <FeedbackModal handleCloseClick={handleFeedbackModalClose} /> + ) + + const mockPlatform = 'platform' + const mockVendor = 'vendor' + const mockUserAgent = 'userAgent' + Object.defineProperty(navigator, 'platform', { value: mockPlatform }) + Object.defineProperty(navigator, 'vendor', { value: mockVendor }) + Object.defineProperty(navigator, 'userAgent', { value: mockUserAgent }) + + const expectedMailData = { + mode: 'from', + to: [{ name: 'Support', email: 'ecolyo@grandlyon.com' }], + subject: '[Ecolyo] - Feedbacks - feedback.type_bug', + parts: [ + { + type: 'text/plain', + body: + 'Type: feedback.type_bug\n' + + '\n' + + 'Description:\n' + + 'La description\n' + + 'Ecolyo\n' + + 'v0.0.0\n' + + '\n' + + 'Location: http://localhost/\n' + + '\n' + + 'Browser:\n' + + 'On null\n' + + 'From null\n' + + 'null\n' + + '\n' + + 'Navigator:' + + `\nOn ${mockPlatform}` + + `\nFrom ${mockVendor}` + + `\n${mockUserAgent}`, + }, + ], + } + + wrapper + .find('div.fb-selector-item') + .first() + .simulate('click') + wrapper + .find('#idFeedbackDescription') + .simulate('change', { target: { value: 'La description' } }) + wrapper.find(MuiButton).simulate('click') + + expect(mockSendMail).toHaveBeenCalledWith( + expect.anything(), + expectedMailData + ) + }) + it('should close the modal and reset the inputs', () => { + mockUseDispatch.mockReturnValue(jest.fn()) + mockUseSelector.mockReturnValue(userChallengeExplo1OnGoing) + const wrapper = shallow( + <FeedbackModal handleCloseClick={handleFeedbackModalClose} /> + ) + wrapper + .find('#idFeedbackDescription') + .simulate('change', { target: { value: 'La description' } }) + wrapper + .find(Modal) + .dive() + .find(StyledIconButton) + .simulate('click') + expect(handleFeedbackModalClose).toHaveBeenCalledTimes(1) + setTimeout(() => { + expect(wrapper.find('#idFeedbackDescription').prop('value')).toBeNull() + }) + }) +}) diff --git a/src/components/Header/CozyBar.spec.tsx b/src/components/Header/CozyBar.spec.tsx index cb2e88fc841319fc47bcfda33e329a9ee1bdc116..2e612a0935dcd2cfe5913544793da432a8a3fd3a 100644 --- a/src/components/Header/CozyBar.spec.tsx +++ b/src/components/Header/CozyBar.spec.tsx @@ -1,100 +1,100 @@ -import React from 'react' -import { mount } from 'enzyme' -import { Provider } from 'react-redux' -import configureStore from 'redux-mock-store' -import CozyBar from 'components/Header/CozyBar' -import * as ModalAction from 'store/modal/modal.actions' -import { globalStateData } from '../../../test/__mocks__/globalStateData.mock' -import { modalStateData } from '../../../test/__mocks__/modalStateData.mock' -import { ScreenType } from 'enum/screen.enum' - -jest.mock('cozy-ui/transpiled/react/I18n', () => { - return { - useI18n: jest.fn(() => { - return { - t: (str: string) => str, - } - }), - } -}) - -const mockGoBack = jest.fn() -jest.mock('react-router-dom', () => ({ - useHistory: () => ({ - goBack: mockGoBack, - }), -})) - -const mockStore = configureStore([]) - -describe('CozyBar component', () => { - it('should be rendered correctly', () => { - const store = mockStore({ - ecolyo: { - global: globalStateData, - }, - }) - const wrapper = mount( - <Provider store={store}> - <CozyBar /> - </Provider> - ) - expect(wrapper.find('BarCenter')).toHaveLength(1) - expect(wrapper.find('BarRight')).toHaveLength(1) - }) - - it('should call handleClickBack when back button is clicked', () => { - const store = mockStore({ - ecolyo: { - global: globalStateData, - }, - }) - const wrapper = mount( - <Provider store={store}> - <CozyBar displayBackArrow={true} /> - </Provider> - ) - expect(wrapper.find('BarLeft')).toHaveLength(1) - wrapper - .find('BarLeft') - .find('.cv-button') - .first() - .simulate('click') - expect(mockGoBack).toHaveBeenCalled() - }) - - it('should call handleClickFeedbacks when feedback button is clicked', () => { - const store = mockStore({ - ecolyo: { - global: globalStateData, - modal: modalStateData, - }, - }) - const wrapper = mount( - <Provider store={store}> - <CozyBar /> - </Provider> - ) - const updateModalSpy = jest.spyOn(ModalAction, 'updateModalIsFeedbacksOpen') - wrapper - .find('BarRight') - .find('.cv-button') - .first() - .simulate('click') - expect(updateModalSpy).toHaveBeenCalledWith(true) - }) - - it('should not be rendered with screen type different from mobile', () => { - const store = mockStore({ - ecolyo: { - global: { ...globalStateData, screenType: ScreenType.DESKTOP }, - }, - }) - const wrapper = mount( - <Provider store={store}> - <CozyBar /> - </Provider> - ) - expect(wrapper).toEqual({}) - }) -}) +import React from 'react' +import { mount } from 'enzyme' +import { Provider } from 'react-redux' +import configureStore from 'redux-mock-store' +import CozyBar from 'components/Header/CozyBar' +import * as ModalAction from 'store/modal/modal.actions' +import { globalStateData } from '../../../tests/__mocks__/globalStateData.mock' +import { modalStateData } from '../../../tests/__mocks__/modalStateData.mock' +import { ScreenType } from 'enum/screen.enum' + +jest.mock('cozy-ui/transpiled/react/I18n', () => { + return { + useI18n: jest.fn(() => { + return { + t: (str: string) => str, + } + }), + } +}) + +const mockGoBack = jest.fn() +jest.mock('react-router-dom', () => ({ + useHistory: () => ({ + goBack: mockGoBack, + }), +})) + +const mockStore = configureStore([]) + +describe('CozyBar component', () => { + it('should be rendered correctly', () => { + const store = mockStore({ + ecolyo: { + global: globalStateData, + }, + }) + const wrapper = mount( + <Provider store={store}> + <CozyBar /> + </Provider> + ) + expect(wrapper.find('BarCenter')).toHaveLength(1) + expect(wrapper.find('BarRight')).toHaveLength(1) + }) + + it('should call handleClickBack when back button is clicked', () => { + const store = mockStore({ + ecolyo: { + global: globalStateData, + }, + }) + const wrapper = mount( + <Provider store={store}> + <CozyBar displayBackArrow={true} /> + </Provider> + ) + expect(wrapper.find('BarLeft')).toHaveLength(1) + wrapper + .find('BarLeft') + .find('.cv-button') + .first() + .simulate('click') + expect(mockGoBack).toHaveBeenCalled() + }) + + it('should call handleClickFeedbacks when feedback button is clicked', () => { + const store = mockStore({ + ecolyo: { + global: globalStateData, + modal: modalStateData, + }, + }) + const wrapper = mount( + <Provider store={store}> + <CozyBar /> + </Provider> + ) + const updateModalSpy = jest.spyOn(ModalAction, 'updateModalIsFeedbacksOpen') + wrapper + .find('BarRight') + .find('.cv-button') + .first() + .simulate('click') + expect(updateModalSpy).toHaveBeenCalledWith(true) + }) + + it('should not be rendered with screen type different from mobile', () => { + const store = mockStore({ + ecolyo: { + global: { ...globalStateData, screenType: ScreenType.DESKTOP }, + }, + }) + const wrapper = mount( + <Provider store={store}> + <CozyBar /> + </Provider> + ) + expect(wrapper).toEqual({}) + }) +}) diff --git a/src/components/Header/Header.spec.tsx b/src/components/Header/Header.spec.tsx index 08374eafdf34ed1452ce490a7aa3b362f8e80bf2..60c6c69a1753df29da79b1d88dd872bc2f4ed080 100644 --- a/src/components/Header/Header.spec.tsx +++ b/src/components/Header/Header.spec.tsx @@ -4,7 +4,7 @@ import { Provider } from 'react-redux' import configureStore from 'redux-mock-store' import * as ModalAction from 'store/modal/modal.actions' import Header from 'components/Header/Header' -import { globalStateData } from '../../../test/__mocks__/globalStateData.mock' +import { globalStateData } from '../../../tests/__mocks__/globalStateData.mock' import { ScreenType } from 'enum/screen.enum' diff --git a/src/components/Home/ConsumptionDetails.spec.tsx b/src/components/Home/ConsumptionDetails.spec.tsx index 1784cd6794e0ea1dbc30f66f7862e5e6f40140ff..9bf79a13482ddea17b480df0b2c8cea801f09e0f 100644 --- a/src/components/Home/ConsumptionDetails.spec.tsx +++ b/src/components/Home/ConsumptionDetails.spec.tsx @@ -1,109 +1,109 @@ -import React from 'react' -import { mount } from 'enzyme' -import ConsumptionDetails from './ConsumptionDetails' -import * as reactRedux from 'react-redux' -import { TimeStep } from 'enum/timeStep.enum' -import { FluidType } from 'enum/fluid.enum' -import { - createMockStore, - mockInitialChartState, - mockInitialEcolyoState, - mockInitialGlobalState, -} from '../../../test/__mocks__/store' -import { Provider } from 'react-redux' -import { BrowserRouter } from 'react-router-dom' - -jest.mock('cozy-ui/transpiled/react/I18n', () => { - return { - useI18n: jest.fn(() => { - return { - t: (str: string) => str, - } - }), - } -}) - -const mockUseSelector = jest.spyOn(reactRedux, 'useSelector') - -describe('ConsumptionDetails component', () => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let store: any - - beforeEach(() => { - store = createMockStore(mockInitialEcolyoState) - mockUseSelector.mockClear() - }) - it('should be rendered correctly', () => { - mockUseSelector.mockReturnValue({ - fluidStatus: mockInitialGlobalState.fluidStatus, - fluidTypes: [FluidType.ELECTRICITY], - selectedDate: mockInitialChartState.selectedDate, - currentTimeStep: TimeStep.WEEK, - currentIndex: mockInitialChartState.currentIndex, - currentDatachart: mockInitialChartState.currentDatachart, - }) - const wrapper = mount( - <Provider store={store}> - <BrowserRouter> - <ConsumptionDetails fluidType={FluidType.ELECTRICITY} /> - </BrowserRouter> - </Provider> - ) - expect(wrapper).toMatchSnapshot() - }) - - it('should not render connection card ', () => { - mockUseSelector.mockReturnValue({ - fluidStatus: mockInitialGlobalState.fluidStatus, - fluidTypes: [FluidType.ELECTRICITY, FluidType.GAS, FluidType.WATER], - selectedDate: mockInitialChartState.selectedDate, - currentTimeStep: TimeStep.WEEK, - currentIndex: mockInitialChartState.currentIndex, - currentDatachart: mockInitialChartState.currentDatachart, - }) - const wrapper = mount( - <Provider store={store}> - <BrowserRouter> - <ConsumptionDetails fluidType={FluidType.MULTIFLUID} /> - </BrowserRouter> - </Provider> - ) - expect(wrapper.contains('.fluidcard-link')).toBeFalsy() - }) - it('should render one connection card ', () => { - mockUseSelector.mockReturnValue({ - fluidStatus: mockInitialGlobalState.fluidStatus, - fluidTypes: [FluidType.ELECTRICITY, FluidType.GAS], - selectedDate: mockInitialChartState.selectedDate, - currentTimeStep: TimeStep.WEEK, - currentIndex: mockInitialChartState.currentIndex, - currentDatachart: mockInitialChartState.currentDatachart, - }) - const wrapper = mount( - <Provider store={store}> - <BrowserRouter> - <ConsumptionDetails fluidType={FluidType.MULTIFLUID} /> - </BrowserRouter> - </Provider> - ) - expect(wrapper.find('.fluidcard-link')).toBeTruthy() - }) - it('should not render connection card and show multifluid link', () => { - mockUseSelector.mockReturnValue({ - fluidStatus: mockInitialGlobalState.fluidStatus, - fluidTypes: [FluidType.ELECTRICITY, FluidType.GAS], - selectedDate: mockInitialChartState.selectedDate, - currentTimeStep: TimeStep.WEEK, - currentIndex: mockInitialChartState.currentIndex, - currentDatachart: mockInitialChartState.currentDatachart, - }) - const wrapper = mount( - <Provider store={store}> - <BrowserRouter> - <ConsumptionDetails fluidType={FluidType.ELECTRICITY} /> - </BrowserRouter> - </Provider> - ) - expect(wrapper.find('.multi-link')).toBeTruthy() - }) -}) +import React from 'react' +import { mount } from 'enzyme' +import ConsumptionDetails from './ConsumptionDetails' +import * as reactRedux from 'react-redux' +import { TimeStep } from 'enum/timeStep.enum' +import { FluidType } from 'enum/fluid.enum' +import { + createMockStore, + mockInitialChartState, + mockInitialEcolyoState, + mockInitialGlobalState, +} from '../../../tests/__mocks__/store' +import { Provider } from 'react-redux' +import { BrowserRouter } from 'react-router-dom' + +jest.mock('cozy-ui/transpiled/react/I18n', () => { + return { + useI18n: jest.fn(() => { + return { + t: (str: string) => str, + } + }), + } +}) + +const mockUseSelector = jest.spyOn(reactRedux, 'useSelector') + +describe('ConsumptionDetails component', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let store: any + + beforeEach(() => { + store = createMockStore(mockInitialEcolyoState) + mockUseSelector.mockClear() + }) + it('should be rendered correctly', () => { + mockUseSelector.mockReturnValue({ + fluidStatus: mockInitialGlobalState.fluidStatus, + fluidTypes: [FluidType.ELECTRICITY], + selectedDate: mockInitialChartState.selectedDate, + currentTimeStep: TimeStep.WEEK, + currentIndex: mockInitialChartState.currentIndex, + currentDatachart: mockInitialChartState.currentDatachart, + }) + const wrapper = mount( + <Provider store={store}> + <BrowserRouter> + <ConsumptionDetails fluidType={FluidType.ELECTRICITY} /> + </BrowserRouter> + </Provider> + ) + expect(wrapper).toMatchSnapshot() + }) + + it('should not render connection card ', () => { + mockUseSelector.mockReturnValue({ + fluidStatus: mockInitialGlobalState.fluidStatus, + fluidTypes: [FluidType.ELECTRICITY, FluidType.GAS, FluidType.WATER], + selectedDate: mockInitialChartState.selectedDate, + currentTimeStep: TimeStep.WEEK, + currentIndex: mockInitialChartState.currentIndex, + currentDatachart: mockInitialChartState.currentDatachart, + }) + const wrapper = mount( + <Provider store={store}> + <BrowserRouter> + <ConsumptionDetails fluidType={FluidType.MULTIFLUID} /> + </BrowserRouter> + </Provider> + ) + expect(wrapper.contains('.fluidcard-link')).toBeFalsy() + }) + it('should render one connection card ', () => { + mockUseSelector.mockReturnValue({ + fluidStatus: mockInitialGlobalState.fluidStatus, + fluidTypes: [FluidType.ELECTRICITY, FluidType.GAS], + selectedDate: mockInitialChartState.selectedDate, + currentTimeStep: TimeStep.WEEK, + currentIndex: mockInitialChartState.currentIndex, + currentDatachart: mockInitialChartState.currentDatachart, + }) + const wrapper = mount( + <Provider store={store}> + <BrowserRouter> + <ConsumptionDetails fluidType={FluidType.MULTIFLUID} /> + </BrowserRouter> + </Provider> + ) + expect(wrapper.find('.fluidcard-link')).toBeTruthy() + }) + it('should not render connection card and show multifluid link', () => { + mockUseSelector.mockReturnValue({ + fluidStatus: mockInitialGlobalState.fluidStatus, + fluidTypes: [FluidType.ELECTRICITY, FluidType.GAS], + selectedDate: mockInitialChartState.selectedDate, + currentTimeStep: TimeStep.WEEK, + currentIndex: mockInitialChartState.currentIndex, + currentDatachart: mockInitialChartState.currentDatachart, + }) + const wrapper = mount( + <Provider store={store}> + <BrowserRouter> + <ConsumptionDetails fluidType={FluidType.ELECTRICITY} /> + </BrowserRouter> + </Provider> + ) + expect(wrapper.find('.multi-link')).toBeTruthy() + }) +}) diff --git a/src/components/Home/HomeView.spec.tsx b/src/components/Home/HomeView.spec.tsx index a56b44d2ed5dbe97ec3d3e318153a784a81cdb41..386d5dce3cfc1ea328947311075daa17cc6a5181 100644 --- a/src/components/Home/HomeView.spec.tsx +++ b/src/components/Home/HomeView.spec.tsx @@ -1,114 +1,114 @@ -/* eslint-disable react/display-name */ -import React from 'react' -import { mount } from 'enzyme' -import { Provider } from 'react-redux' -import * as reactRedux from 'react-redux' -import { - createMockStore, - mockInitialEcolyoState, -} from '../../../test/__mocks__/store' -import * as chartActions from 'store/chart/chart.actions' -import HomeView from 'components/Home/HomeView' -import { TimeStep } from 'enum/timeStep.enum' -import Header from 'components/Header/Header' -import StyledSpinner from 'components/CommonKit/Spinner/StyledSpinner' - -jest.mock('cozy-ui/transpiled/react/I18n', () => { - return { - useI18n: jest.fn(() => { - return { - t: (str: string) => str, - } - }), - } -}) - -jest.mock('components/Header/CozyBar', () => () => <div id="cozybar"></div>) -jest.mock('components/DateNavigator/DateNavigator', () => () => ( - <div id="datenavigator"></div> -)) -jest.mock('components/FluidChart/FluidChart', () => () => ( - <div id="fluidchart"></div> -)) -jest.mock('components/Home/ConsumptionDetails', () => () => ( - <div id="consumptiondetails"></div> -)) -jest.mock('components/Home/OldFluidDataModal', () => () => ( - <div id="oldfluiddatamodal"></div> -)) -jest.mock('components/Konnector/KonnectorViewerList', () => () => ( - <div id="konnectorviewerlist"></div> -)) - -const useSelectorSpy = jest.spyOn(reactRedux, 'useSelector') -const useDispatchSpy = jest.spyOn(reactRedux, 'useDispatch') -const setCurrentTimeStepSpy = jest.spyOn(chartActions, 'setCurrentTimeStep') - -describe('SingleFluidView component', () => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let store: any - beforeEach(() => { - store = createMockStore(mockInitialEcolyoState) - useDispatchSpy.mockClear() - setCurrentTimeStepSpy.mockClear() - }) - - it('should be rendered correctly', () => { - useSelectorSpy.mockReturnValue({ - fluidTypes: [0], - loading: false, - }) - const wrapper = mount( - <Provider store={store}> - <HomeView /> - </Provider> - ) - expect(wrapper.find('#cozybar')).toBeTruthy() - expect(wrapper.find(Header)).toBeTruthy() - expect(wrapper.find('#datenavigator')).toBeTruthy() - expect(wrapper.find('#fluidcard')).toBeTruthy() - expect(wrapper.find('#consumptiondetails')).toBeTruthy() - }) - - it('should display a spinner', () => { - useSelectorSpy.mockReturnValue({ - fluidTypes: [0], - loading: true, - }) - const wrapper = mount( - <Provider store={store}> - <HomeView /> - </Provider> - ) - expect(wrapper.find('#cozybar')).toBeTruthy() - expect(wrapper.find(Header)).toBeTruthy() - expect(wrapper.find('#datenavigator')).toBeTruthy() - expect(wrapper.find(StyledSpinner)).toBeTruthy() - }) - - it('should display the konnector viewer list', () => { - const wrapper = mount( - <Provider store={store}> - <HomeView /> - </Provider> - ) - expect(wrapper.find('#cozybar')).toBeTruthy() - expect(wrapper.find(Header)).toBeTruthy() - expect(wrapper.find('#konnectorviewerlist')).toBeTruthy() - }) - - it('should set CurrentTimeStep to WEEK when timeStep = HALF_AN_HOUR', () => { - useSelectorSpy.mockReturnValue({ - fluidTypes: [0], - currentTimeStep: TimeStep.HALF_AN_HOUR, - loading: false, - }) - mount( - <Provider store={store}> - <HomeView /> - </Provider> - ) - expect(setCurrentTimeStepSpy).toBeCalledTimes(1) - expect(setCurrentTimeStepSpy).toHaveBeenCalledWith(TimeStep.WEEK) - }) -}) +/* eslint-disable react/display-name */ +import React from 'react' +import { mount } from 'enzyme' +import { Provider } from 'react-redux' +import * as reactRedux from 'react-redux' +import { + createMockStore, + mockInitialEcolyoState, +} from '../../../tests/__mocks__/store' +import * as chartActions from 'store/chart/chart.actions' +import HomeView from 'components/Home/HomeView' +import { TimeStep } from 'enum/timeStep.enum' +import Header from 'components/Header/Header' +import StyledSpinner from 'components/CommonKit/Spinner/StyledSpinner' + +jest.mock('cozy-ui/transpiled/react/I18n', () => { + return { + useI18n: jest.fn(() => { + return { + t: (str: string) => str, + } + }), + } +}) + +jest.mock('components/Header/CozyBar', () => () => <div id="cozybar"></div>) +jest.mock('components/DateNavigator/DateNavigator', () => () => ( + <div id="datenavigator"></div> +)) +jest.mock('components/FluidChart/FluidChart', () => () => ( + <div id="fluidchart"></div> +)) +jest.mock('components/Home/ConsumptionDetails', () => () => ( + <div id="consumptiondetails"></div> +)) +jest.mock('components/Home/OldFluidDataModal', () => () => ( + <div id="oldfluiddatamodal"></div> +)) +jest.mock('components/Konnector/KonnectorViewerList', () => () => ( + <div id="konnectorviewerlist"></div> +)) + +const useSelectorSpy = jest.spyOn(reactRedux, 'useSelector') +const useDispatchSpy = jest.spyOn(reactRedux, 'useDispatch') +const setCurrentTimeStepSpy = jest.spyOn(chartActions, 'setCurrentTimeStep') + +describe('SingleFluidView component', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let store: any + beforeEach(() => { + store = createMockStore(mockInitialEcolyoState) + useDispatchSpy.mockClear() + setCurrentTimeStepSpy.mockClear() + }) + + it('should be rendered correctly', () => { + useSelectorSpy.mockReturnValue({ + fluidTypes: [0], + loading: false, + }) + const wrapper = mount( + <Provider store={store}> + <HomeView /> + </Provider> + ) + expect(wrapper.find('#cozybar')).toBeTruthy() + expect(wrapper.find(Header)).toBeTruthy() + expect(wrapper.find('#datenavigator')).toBeTruthy() + expect(wrapper.find('#fluidcard')).toBeTruthy() + expect(wrapper.find('#consumptiondetails')).toBeTruthy() + }) + + it('should display a spinner', () => { + useSelectorSpy.mockReturnValue({ + fluidTypes: [0], + loading: true, + }) + const wrapper = mount( + <Provider store={store}> + <HomeView /> + </Provider> + ) + expect(wrapper.find('#cozybar')).toBeTruthy() + expect(wrapper.find(Header)).toBeTruthy() + expect(wrapper.find('#datenavigator')).toBeTruthy() + expect(wrapper.find(StyledSpinner)).toBeTruthy() + }) + + it('should display the konnector viewer list', () => { + const wrapper = mount( + <Provider store={store}> + <HomeView /> + </Provider> + ) + expect(wrapper.find('#cozybar')).toBeTruthy() + expect(wrapper.find(Header)).toBeTruthy() + expect(wrapper.find('#konnectorviewerlist')).toBeTruthy() + }) + + it('should set CurrentTimeStep to WEEK when timeStep = HALF_AN_HOUR', () => { + useSelectorSpy.mockReturnValue({ + fluidTypes: [0], + currentTimeStep: TimeStep.HALF_AN_HOUR, + loading: false, + }) + mount( + <Provider store={store}> + <HomeView /> + </Provider> + ) + expect(setCurrentTimeStepSpy).toBeCalledTimes(1) + expect(setCurrentTimeStepSpy).toHaveBeenCalledWith(TimeStep.WEEK) + }) +}) diff --git a/src/components/HomeCards/AddKonnectorCard.spec.tsx b/src/components/HomeCards/AddKonnectorCard.spec.tsx index 236eb909e07f604daa721ab01d0d546e254f79d0..7840621f083c81cd112a2baf014c25f9585271b8 100644 --- a/src/components/HomeCards/AddKonnectorCard.spec.tsx +++ b/src/components/HomeCards/AddKonnectorCard.spec.tsx @@ -1,39 +1,39 @@ -import React from 'react' -import { shallow } from 'enzyme' -import { FluidType } from 'enum/fluid.enum' -import AddKonnectorCard from './AddKonnectorCard' - -import { fluidStatusData } from '../../../test/__mocks__/fluidStatusData.mock' - -jest.mock('cozy-ui/transpiled/react/I18n', () => { - return { - useI18n: jest.fn(() => { - return { - t: (str: string) => str, - } - }), - } -}) - -describe('AddKonnectorCard component', () => { - it('should be rendered correctly', () => { - const component = shallow( - <AddKonnectorCard - fluidType={FluidType.ELECTRICITY} - fluidStatus={fluidStatusData[0]} - /> - ).getElement() - expect(component).toMatchSnapshot() - }) - it('should be rendered with Elec connexion', () => { - const component = shallow( - <AddKonnectorCard - fluidType={FluidType.ELECTRICITY} - fluidStatus={fluidStatusData[0]} - /> - ) - expect(component.find('.add-konnector-title').text()).toContain( - 'ELECTRICITY' - ) - }) -}) +import React from 'react' +import { shallow } from 'enzyme' +import { FluidType } from 'enum/fluid.enum' +import AddKonnectorCard from './AddKonnectorCard' + +import { fluidStatusData } from '../../../tests/__mocks__/fluidStatusData.mock' + +jest.mock('cozy-ui/transpiled/react/I18n', () => { + return { + useI18n: jest.fn(() => { + return { + t: (str: string) => str, + } + }), + } +}) + +describe('AddKonnectorCard component', () => { + it('should be rendered correctly', () => { + const component = shallow( + <AddKonnectorCard + fluidType={FluidType.ELECTRICITY} + fluidStatus={fluidStatusData[0]} + /> + ).getElement() + expect(component).toMatchSnapshot() + }) + it('should be rendered with Elec connexion', () => { + const component = shallow( + <AddKonnectorCard + fluidType={FluidType.ELECTRICITY} + fluidStatus={fluidStatusData[0]} + /> + ) + expect(component.find('.add-konnector-title').text()).toContain( + 'ELECTRICITY' + ) + }) +}) diff --git a/src/components/HomeCards/TotalConsumption.spec.tsx b/src/components/HomeCards/TotalConsumption.spec.tsx index 5b92a4442a6ef275271d466bf1d3bf234f840853..431bb7880701b5391ee2d0a85f992ace870456a0 100644 --- a/src/components/HomeCards/TotalConsumption.spec.tsx +++ b/src/components/HomeCards/TotalConsumption.spec.tsx @@ -1,64 +1,64 @@ -import React from 'react' -import { mount } from 'enzyme' -import { FluidType } from 'enum/fluid.enum' -import TotalConsumption from './TotalConsumption' -import { mockInitialChartState } from '../../../test/__mocks__/store' -import { graphData } from '../../../test/__mocks__/datachartData.mock' - -jest.mock('cozy-ui/transpiled/react/I18n', () => { - return { - useI18n: jest.fn(() => { - return { - t: (str: string) => str, - } - }), - } -}) - -describe('TotalConsumption component', () => { - it('should be rendered correctly', () => { - const component = mount( - <TotalConsumption - fluidType={FluidType.ELECTRICITY} - actualData={mockInitialChartState.currentDatachart.actualData} - /> - ) - expect(component).toMatchSnapshot() - }) - it('should render euro value', () => { - const component = mount( - <TotalConsumption - fluidType={FluidType.ELECTRICITY} - actualData={graphData.actualData} - /> - ) - expect( - component - .find('.euro-value') - .first() - .text() - ).toEqual('20,23') - }) - it('should call Converter method', () => { - const mockLoadToEuro = jest.fn() - jest.mock('services/converter.service', () => { - return jest.fn(() => { - return { - loadToEuro: mockLoadToEuro, - } - }) - }) - const component = mount( - <TotalConsumption - fluidType={FluidType.MULTIFLUID} - actualData={graphData.actualData} - /> - ) - expect( - component - .find('.euro-value') - .first() - .text() - ).toEqual('130,84') - }) -}) +import React from 'react' +import { mount } from 'enzyme' +import { FluidType } from 'enum/fluid.enum' +import TotalConsumption from './TotalConsumption' +import { mockInitialChartState } from '../../../tests/__mocks__/store' +import { graphData } from '../../../tests/__mocks__/datachartData.mock' + +jest.mock('cozy-ui/transpiled/react/I18n', () => { + return { + useI18n: jest.fn(() => { + return { + t: (str: string) => str, + } + }), + } +}) + +describe('TotalConsumption component', () => { + it('should be rendered correctly', () => { + const component = mount( + <TotalConsumption + fluidType={FluidType.ELECTRICITY} + actualData={mockInitialChartState.currentDatachart.actualData} + /> + ) + expect(component).toMatchSnapshot() + }) + it('should render euro value', () => { + const component = mount( + <TotalConsumption + fluidType={FluidType.ELECTRICITY} + actualData={graphData.actualData} + /> + ) + expect( + component + .find('.euro-value') + .first() + .text() + ).toEqual('20,23') + }) + it('should call Converter method', () => { + const mockLoadToEuro = jest.fn() + jest.mock('services/converter.service', () => { + return jest.fn(() => { + return { + loadToEuro: mockLoadToEuro, + } + }) + }) + const component = mount( + <TotalConsumption + fluidType={FluidType.MULTIFLUID} + actualData={graphData.actualData} + /> + ) + expect( + component + .find('.euro-value') + .first() + .text() + ).toEqual('130,84') + }) +}) diff --git a/src/components/Hooks/useExploration.spec.tsx b/src/components/Hooks/useExploration.spec.tsx index 9aabf0e0e43571db8ec0c2b5d4ac559ac71a7150..13d4e02e9651ad48df2054bc9cb3efe584cf761c 100644 --- a/src/components/Hooks/useExploration.spec.tsx +++ b/src/components/Hooks/useExploration.spec.tsx @@ -1,23 +1,23 @@ -import * as reactRedux from 'react-redux' -import { renderHook, act } from '@testing-library/react-hooks' -import useExploration from 'components/Hooks/useExploration' -import { UserExplorationID } from 'enum/userExploration.enum' -import { userChallengeExplo1OnGoing } from '../../../test/__mocks__/userChallengeData.mock' - -const dispatchMock = jest.fn() -const mockUseSelector = jest.spyOn(reactRedux, 'useSelector') -const mockUseDispatch = jest.spyOn(reactRedux, 'useDispatch') - -describe('useExploration Hooks', () => { - it('should return "EXPLORATION001"', () => { - mockUseDispatch.mockReturnValue(dispatchMock) - mockUseSelector.mockReturnValue(userChallengeExplo1OnGoing) - - const { result } = renderHook(() => useExploration()) - - act(() => { - result.current[1](UserExplorationID.EXPLORATION001) - }) - expect(result.current[0]).toBe(UserExplorationID.EXPLORATION001) - }) -}) +import * as reactRedux from 'react-redux' +import { renderHook, act } from '@testing-library/react-hooks' +import useExploration from 'components/Hooks/useExploration' +import { UserExplorationID } from 'enum/userExploration.enum' +import { userChallengeExplo1OnGoing } from '../../../tests/__mocks__/userChallengeData.mock' + +const dispatchMock = jest.fn() +const mockUseSelector = jest.spyOn(reactRedux, 'useSelector') +const mockUseDispatch = jest.spyOn(reactRedux, 'useDispatch') + +describe('useExploration Hooks', () => { + it('should return "EXPLORATION001"', () => { + mockUseDispatch.mockReturnValue(dispatchMock) + mockUseSelector.mockReturnValue(userChallengeExplo1OnGoing) + + const { result } = renderHook(() => useExploration()) + + act(() => { + result.current[1](UserExplorationID.EXPLORATION001) + }) + expect(result.current[0]).toBe(UserExplorationID.EXPLORATION001) + }) +}) diff --git a/src/components/Navbar/Navbar.spec.tsx b/src/components/Navbar/Navbar.spec.tsx index 62bd7a354398745acdc9a8c3ea94b723d8495bea..441ab394586a86fa504c7edafedb5ccffa583130 100644 --- a/src/components/Navbar/Navbar.spec.tsx +++ b/src/components/Navbar/Navbar.spec.tsx @@ -4,7 +4,7 @@ import { BrowserRouter } from 'react-router-dom' import { Provider } from 'react-redux' import configureStore from 'redux-mock-store' import Navbar from 'components/Navbar/Navbar' -import { globalStateData } from '../../../test/__mocks__/globalStateData.mock' +import { globalStateData } from '../../../tests/__mocks__/globalStateData.mock' jest.mock('cozy-ui/transpiled/react/I18n', () => { return { diff --git a/src/components/Options/ProfileTypeOptions.spec.tsx b/src/components/Options/ProfileTypeOptions.spec.tsx index 57c288f493e00efbd2fa14b2fa7b2dca0cf8ce14..82142e12e69ef006c8cb8219ff36e97323ecc4e5 100644 --- a/src/components/Options/ProfileTypeOptions.spec.tsx +++ b/src/components/Options/ProfileTypeOptions.spec.tsx @@ -3,7 +3,7 @@ import { mount } from 'enzyme' import { Provider } from 'react-redux' import configureStore from 'redux-mock-store' import ProfileTypeOptions from 'components/Options/ProfileTypeOptions' -import { profileData } from '../../../test/__mocks__/profile.mock' +import { profileData } from '../../../tests/__mocks__/profile.mock' import StyledCard from 'components/CommonKit/Card/StyledCard' import StyledIcon from 'components/CommonKit/Icon/StyledIcon' import profileIcon from 'assets/icons/ico/profile.svg' @@ -13,7 +13,7 @@ import { IndividualOrCollective, ThreeChoicesAnswer, } from 'enum/profileType.enum' -import { mockInitialChallengeState } from '../../../test/__mocks__/store' +import { mockInitialChallengeState } from '../../../tests/__mocks__/store' jest.mock('cozy-ui/transpiled/react/I18n', () => { return { diff --git a/src/components/Options/ReportOptions.spec.tsx b/src/components/Options/ReportOptions.spec.tsx index 676aeb707dfdc4394ae2c8bff1e7abf007c049d8..d1ca8851eae03b43f51c7018decebcc9438e0bcb 100644 --- a/src/components/Options/ReportOptions.spec.tsx +++ b/src/components/Options/ReportOptions.spec.tsx @@ -1,70 +1,70 @@ -import React from 'react' -import { mount } from 'enzyme' -import { Provider } from 'react-redux' -import ReportOptions from 'components/Options/ReportOptions' -import { - createMockStore, - mockInitialEcolyoState, -} from '../../../test/__mocks__/store' -import * as profileActions from 'store/profile/profile.actions' - -jest.mock('cozy-ui/transpiled/react/I18n', () => { - return { - useI18n: jest.fn(() => { - return { - t: (str: string) => str, - } - }), - } -}) - -const mockUpdateProfile = jest.fn() -jest.mock('services/profile.service', () => { - return jest.fn(() => { - return { - updateProfile: mockUpdateProfile, - } - }) -}) - -const updateProfileSpy = jest.spyOn(profileActions, 'updateProfile') - -describe('ReportOptions component', () => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let store: any - beforeEach(() => { - store = createMockStore(mockInitialEcolyoState) - updateProfileSpy.mockClear() - }) - - it('should be rendered with sendAnalysisNotification to false', () => { - const wrapper = mount( - <Provider store={store}> - <ReportOptions /> - </Provider> - ) - expect(wrapper.find('input')).toHaveLength(1) - expect( - wrapper - .find('#switch-report') - .first() - .props().checked - ).toBeFalsy() - }) - - it('should update the profile with sendAnalysisNotification to true', () => { - const wrapper = mount( - <Provider store={store}> - <ReportOptions /> - </Provider> - ) - wrapper - .find('#switch-report') - .first() - .simulate('change', { target: { checked: 'true' } }) - expect(updateProfileSpy).toBeCalledTimes(1) - expect(updateProfileSpy).toHaveBeenCalledWith({ - sendAnalysisNotification: true, - }) - }) -}) +import React from 'react' +import { mount } from 'enzyme' +import { Provider } from 'react-redux' +import ReportOptions from 'components/Options/ReportOptions' +import { + createMockStore, + mockInitialEcolyoState, +} from '../../../tests/__mocks__/store' +import * as profileActions from 'store/profile/profile.actions' + +jest.mock('cozy-ui/transpiled/react/I18n', () => { + return { + useI18n: jest.fn(() => { + return { + t: (str: string) => str, + } + }), + } +}) + +const mockUpdateProfile = jest.fn() +jest.mock('services/profile.service', () => { + return jest.fn(() => { + return { + updateProfile: mockUpdateProfile, + } + }) +}) + +const updateProfileSpy = jest.spyOn(profileActions, 'updateProfile') + +describe('ReportOptions component', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let store: any + beforeEach(() => { + store = createMockStore(mockInitialEcolyoState) + updateProfileSpy.mockClear() + }) + + it('should be rendered with sendAnalysisNotification to false', () => { + const wrapper = mount( + <Provider store={store}> + <ReportOptions /> + </Provider> + ) + expect(wrapper.find('input')).toHaveLength(1) + expect( + wrapper + .find('#switch-report') + .first() + .props().checked + ).toBeFalsy() + }) + + it('should update the profile with sendAnalysisNotification to true', () => { + const wrapper = mount( + <Provider store={store}> + <ReportOptions /> + </Provider> + ) + wrapper + .find('#switch-report') + .first() + .simulate('change', { target: { checked: 'true' } }) + expect(updateProfileSpy).toBeCalledTimes(1) + expect(updateProfileSpy).toHaveBeenCalledWith({ + sendAnalysisNotification: true, + }) + }) +}) diff --git a/src/components/ProfileType/ProfileTypeFinished.spec.tsx b/src/components/ProfileType/ProfileTypeFinished.spec.tsx index 8aade596144dc70ef50b32805f2917042dfe7344..5500282f8580a31156513f7f51cd4f14d101115d 100644 --- a/src/components/ProfileType/ProfileTypeFinished.spec.tsx +++ b/src/components/ProfileType/ProfileTypeFinished.spec.tsx @@ -1,36 +1,36 @@ -import React from 'react' -import { Provider } from 'react-redux' -import { mount } from 'enzyme' -import { - createMockStore, - mockInitialEcolyoState, -} from '../../../test/__mocks__/store' -import ProfileTypeFinished from './ProfileTypeFinished' -import { mockProfileType } from '../../../test/__mocks__/profileType.mock' - -jest.mock('cozy-ui/transpiled/react/I18n', () => { - return { - useI18n: jest.fn(() => { - return { - t: (str: string) => str, - } - }), - } -}) - -describe('ProfileTypeView component', () => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let store: any - beforeEach(() => { - store = createMockStore(mockInitialEcolyoState) - }) - - it('should be rendered correctly', () => { - const wrapper = mount( - <Provider store={store}> - <ProfileTypeFinished profileType={mockProfileType} /> - </Provider> - ) - expect(wrapper.find('profile-type-finished-card')).toBeTruthy() - }) -}) +import React from 'react' +import { Provider } from 'react-redux' +import { mount } from 'enzyme' +import { + createMockStore, + mockInitialEcolyoState, +} from '../../../tests/__mocks__/store' +import ProfileTypeFinished from './ProfileTypeFinished' +import { mockProfileType } from '../../../tests/__mocks__/profileType.mock' + +jest.mock('cozy-ui/transpiled/react/I18n', () => { + return { + useI18n: jest.fn(() => { + return { + t: (str: string) => str, + } + }), + } +}) + +describe('ProfileTypeView component', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let store: any + beforeEach(() => { + store = createMockStore(mockInitialEcolyoState) + }) + + it('should be rendered correctly', () => { + const wrapper = mount( + <Provider store={store}> + <ProfileTypeFinished profileType={mockProfileType} /> + </Provider> + ) + expect(wrapper.find('profile-type-finished-card')).toBeTruthy() + }) +}) diff --git a/src/components/ProfileType/ProfileTypeFormMultiChoice.spec.tsx b/src/components/ProfileType/ProfileTypeFormMultiChoice.spec.tsx index d17e2eb53af088c15e9443bf052c5ea5cf42866d..135d68c8434d11f88c039670283abf371c56d40b 100644 --- a/src/components/ProfileType/ProfileTypeFormMultiChoice.spec.tsx +++ b/src/components/ProfileType/ProfileTypeFormMultiChoice.spec.tsx @@ -1,50 +1,50 @@ -import React from 'react' -import { Provider } from 'react-redux' -import { mount } from 'enzyme' -import { - createMockStore, - mockInitialEcolyoState, -} from '../../../test/__mocks__/store' -import { ProfileTypeStepForm } from 'enum/profileType.enum' -import { - mockProfileType, - mockProfileTypeAnswers, -} from '../../../test/__mocks__/profileType.mock' -import ProfileTypeFormMultiChoice from './ProfileTypeFormMultiChoice' - -jest.mock('cozy-ui/transpiled/react/I18n', () => { - return { - useI18n: jest.fn(() => { - return { - t: (str: string) => str, - } - }), - } -}) - -describe('ProfileTypeFormMultiChoice component', () => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let store: any - beforeEach(() => { - store = createMockStore(mockInitialEcolyoState) - }) - - it('should be rendered correctly', () => { - const mockhandlePrevious = jest.fn() - const mockhandleNext = jest.fn() - const wrapper = mount( - <Provider store={store}> - <ProfileTypeFormMultiChoice - step={ProfileTypeStepForm.COOKING_FLUID} - viewedStep={ProfileTypeStepForm.AREA} - profileType={mockProfileType} - answerType={mockProfileTypeAnswers[1]} - setNextStep={mockhandlePrevious} - setPrevioustStep={mockhandleNext} - isProfileTypeComplete={false} - /> - </Provider> - ) - expect(wrapper.find('input')).toBeTruthy() - }) -}) +import React from 'react' +import { Provider } from 'react-redux' +import { mount } from 'enzyme' +import { + createMockStore, + mockInitialEcolyoState, +} from '../../../tests/__mocks__/store' +import { ProfileTypeStepForm } from 'enum/profileType.enum' +import { + mockProfileType, + mockProfileTypeAnswers, +} from '../../../tests/__mocks__/profileType.mock' +import ProfileTypeFormMultiChoice from './ProfileTypeFormMultiChoice' + +jest.mock('cozy-ui/transpiled/react/I18n', () => { + return { + useI18n: jest.fn(() => { + return { + t: (str: string) => str, + } + }), + } +}) + +describe('ProfileTypeFormMultiChoice component', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let store: any + beforeEach(() => { + store = createMockStore(mockInitialEcolyoState) + }) + + it('should be rendered correctly', () => { + const mockhandlePrevious = jest.fn() + const mockhandleNext = jest.fn() + const wrapper = mount( + <Provider store={store}> + <ProfileTypeFormMultiChoice + step={ProfileTypeStepForm.COOKING_FLUID} + viewedStep={ProfileTypeStepForm.AREA} + profileType={mockProfileType} + answerType={mockProfileTypeAnswers[1]} + setNextStep={mockhandlePrevious} + setPrevioustStep={mockhandleNext} + isProfileTypeComplete={false} + /> + </Provider> + ) + expect(wrapper.find('input')).toBeTruthy() + }) +}) diff --git a/src/components/ProfileType/ProfileTypeFormNumber.spec.tsx b/src/components/ProfileType/ProfileTypeFormNumber.spec.tsx index fb00310e101cf3386abc1bf172444a7858e9ea8c..75c3679b9c50ffdc272c901ab8201aa178d0923b 100644 --- a/src/components/ProfileType/ProfileTypeFormNumber.spec.tsx +++ b/src/components/ProfileType/ProfileTypeFormNumber.spec.tsx @@ -1,50 +1,50 @@ -import React from 'react' -import { Provider } from 'react-redux' -import { mount } from 'enzyme' -import { - createMockStore, - mockInitialEcolyoState, -} from '../../../test/__mocks__/store' -import { ProfileTypeStepForm } from 'enum/profileType.enum' -import { - mockProfileType, - mockProfileTypeAnswers, -} from '../../../test/__mocks__/profileType.mock' -import ProfileTypeFormNumber from './ProfileTypeFormNumber' - -jest.mock('cozy-ui/transpiled/react/I18n', () => { - return { - useI18n: jest.fn(() => { - return { - t: (str: string) => str, - } - }), - } -}) - -describe('ProfileTypeFormNumber component', () => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let store: any - beforeEach(() => { - store = createMockStore(mockInitialEcolyoState) - }) - - it('should be rendered correctly', () => { - const mockhandlePrevious = jest.fn() - const mockhandleNext = jest.fn() - const wrapper = mount( - <Provider store={store}> - <ProfileTypeFormNumber - step={ProfileTypeStepForm.COOKING_FLUID} - viewedStep={ProfileTypeStepForm.AREA} - profileType={mockProfileType} - answerType={mockProfileTypeAnswers[1]} - setNextStep={mockhandlePrevious} - setPrevioustStep={mockhandleNext} - isProfileTypeComplete={false} - /> - </Provider> - ) - expect(wrapper.find('input')).toBeTruthy() - }) -}) +import React from 'react' +import { Provider } from 'react-redux' +import { mount } from 'enzyme' +import { + createMockStore, + mockInitialEcolyoState, +} from '../../../tests/__mocks__/store' +import { ProfileTypeStepForm } from 'enum/profileType.enum' +import { + mockProfileType, + mockProfileTypeAnswers, +} from '../../../tests/__mocks__/profileType.mock' +import ProfileTypeFormNumber from './ProfileTypeFormNumber' + +jest.mock('cozy-ui/transpiled/react/I18n', () => { + return { + useI18n: jest.fn(() => { + return { + t: (str: string) => str, + } + }), + } +}) + +describe('ProfileTypeFormNumber component', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let store: any + beforeEach(() => { + store = createMockStore(mockInitialEcolyoState) + }) + + it('should be rendered correctly', () => { + const mockhandlePrevious = jest.fn() + const mockhandleNext = jest.fn() + const wrapper = mount( + <Provider store={store}> + <ProfileTypeFormNumber + step={ProfileTypeStepForm.COOKING_FLUID} + viewedStep={ProfileTypeStepForm.AREA} + profileType={mockProfileType} + answerType={mockProfileTypeAnswers[1]} + setNextStep={mockhandlePrevious} + setPrevioustStep={mockhandleNext} + isProfileTypeComplete={false} + /> + </Provider> + ) + expect(wrapper.find('input')).toBeTruthy() + }) +}) diff --git a/src/components/ProfileType/ProfileTypeFormNumberSelection.spec.tsx b/src/components/ProfileType/ProfileTypeFormNumberSelection.spec.tsx index b5ed5a3b3fcf865825d01c94c53da6872d7714fc..01aed1c2f334b61f1bdccf7c06a1ca81514928b3 100644 --- a/src/components/ProfileType/ProfileTypeFormNumberSelection.spec.tsx +++ b/src/components/ProfileType/ProfileTypeFormNumberSelection.spec.tsx @@ -1,50 +1,50 @@ -import React from 'react' -import { Provider } from 'react-redux' -import { mount } from 'enzyme' -import { - createMockStore, - mockInitialEcolyoState, -} from '../../../test/__mocks__/store' -import { ProfileTypeStepForm } from 'enum/profileType.enum' -import { - mockProfileType, - mockProfileTypeAnswers, -} from '../../../test/__mocks__/profileType.mock' -import ProfileTypeFormNumberSelection from './ProfileTypeFormNumberSelection' - -jest.mock('cozy-ui/transpiled/react/I18n', () => { - return { - useI18n: jest.fn(() => { - return { - t: (str: string) => str, - } - }), - } -}) - -describe('ProfileTypeFormNumberSelection component', () => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let store: any - beforeEach(() => { - store = createMockStore(mockInitialEcolyoState) - }) - - it('should be rendered correctly', () => { - const mockhandlePrevious = jest.fn() - const mockhandleNext = jest.fn() - const wrapper = mount( - <Provider store={store}> - <ProfileTypeFormNumberSelection - step={ProfileTypeStepForm.COOKING_FLUID} - viewedStep={ProfileTypeStepForm.AREA} - profileType={mockProfileType} - answerType={mockProfileTypeAnswers[3]} - setNextStep={mockhandlePrevious} - setPrevioustStep={mockhandleNext} - isProfileTypeComplete={false} - /> - </Provider> - ) - expect(wrapper.find('input')).toBeTruthy() - }) -}) +import React from 'react' +import { Provider } from 'react-redux' +import { mount } from 'enzyme' +import { + createMockStore, + mockInitialEcolyoState, +} from '../../../tests/__mocks__/store' +import { ProfileTypeStepForm } from 'enum/profileType.enum' +import { + mockProfileType, + mockProfileTypeAnswers, +} from '../../../tests/__mocks__/profileType.mock' +import ProfileTypeFormNumberSelection from './ProfileTypeFormNumberSelection' + +jest.mock('cozy-ui/transpiled/react/I18n', () => { + return { + useI18n: jest.fn(() => { + return { + t: (str: string) => str, + } + }), + } +}) + +describe('ProfileTypeFormNumberSelection component', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let store: any + beforeEach(() => { + store = createMockStore(mockInitialEcolyoState) + }) + + it('should be rendered correctly', () => { + const mockhandlePrevious = jest.fn() + const mockhandleNext = jest.fn() + const wrapper = mount( + <Provider store={store}> + <ProfileTypeFormNumberSelection + step={ProfileTypeStepForm.COOKING_FLUID} + viewedStep={ProfileTypeStepForm.AREA} + profileType={mockProfileType} + answerType={mockProfileTypeAnswers[3]} + setNextStep={mockhandlePrevious} + setPrevioustStep={mockhandleNext} + isProfileTypeComplete={false} + /> + </Provider> + ) + expect(wrapper.find('input')).toBeTruthy() + }) +}) diff --git a/src/components/ProfileType/ProfileTypeFormSingleChoice.spec.tsx b/src/components/ProfileType/ProfileTypeFormSingleChoice.spec.tsx index 7cd5c1e3561218011118dd589c1dd2a76a90bd6f..4732a2f69895376ec239a90957c36eb950643f7d 100644 --- a/src/components/ProfileType/ProfileTypeFormSingleChoice.spec.tsx +++ b/src/components/ProfileType/ProfileTypeFormSingleChoice.spec.tsx @@ -1,50 +1,50 @@ -import React from 'react' -import { Provider } from 'react-redux' -import { mount } from 'enzyme' -import { - createMockStore, - mockInitialEcolyoState, -} from '../../../test/__mocks__/store' -import ProfileTypeFormSingleChoice from './ProfileTypeFormSingleChoice' -import { ProfileTypeStepForm } from 'enum/profileType.enum' -import { - mockProfileType, - mockProfileTypeAnswers, -} from '../../../test/__mocks__/profileType.mock' - -jest.mock('cozy-ui/transpiled/react/I18n', () => { - return { - useI18n: jest.fn(() => { - return { - t: (str: string) => str, - } - }), - } -}) - -describe('ProfileTypeFormSingleChoice component', () => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let store: any - beforeEach(() => { - store = createMockStore(mockInitialEcolyoState) - }) - - it('should be rendered correctly', () => { - const mockhandlePrevious = jest.fn() - const mockhandleNext = jest.fn() - const wrapper = mount( - <Provider store={store}> - <ProfileTypeFormSingleChoice - step={ProfileTypeStepForm.COOKING_FLUID} - viewedStep={ProfileTypeStepForm.AREA} - profileType={mockProfileType} - answerType={mockProfileTypeAnswers[1]} - setNextStep={mockhandlePrevious} - setPrevioustStep={mockhandleNext} - isProfileTypeComplete={false} - /> - </Provider> - ) - expect(wrapper.find('input')).toBeTruthy() - }) -}) +import React from 'react' +import { Provider } from 'react-redux' +import { mount } from 'enzyme' +import { + createMockStore, + mockInitialEcolyoState, +} from '../../../tests/__mocks__/store' +import ProfileTypeFormSingleChoice from './ProfileTypeFormSingleChoice' +import { ProfileTypeStepForm } from 'enum/profileType.enum' +import { + mockProfileType, + mockProfileTypeAnswers, +} from '../../../tests/__mocks__/profileType.mock' + +jest.mock('cozy-ui/transpiled/react/I18n', () => { + return { + useI18n: jest.fn(() => { + return { + t: (str: string) => str, + } + }), + } +}) + +describe('ProfileTypeFormSingleChoice component', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let store: any + beforeEach(() => { + store = createMockStore(mockInitialEcolyoState) + }) + + it('should be rendered correctly', () => { + const mockhandlePrevious = jest.fn() + const mockhandleNext = jest.fn() + const wrapper = mount( + <Provider store={store}> + <ProfileTypeFormSingleChoice + step={ProfileTypeStepForm.COOKING_FLUID} + viewedStep={ProfileTypeStepForm.AREA} + profileType={mockProfileType} + answerType={mockProfileTypeAnswers[1]} + setNextStep={mockhandlePrevious} + setPrevioustStep={mockhandleNext} + isProfileTypeComplete={false} + /> + </Provider> + ) + expect(wrapper.find('input')).toBeTruthy() + }) +}) diff --git a/src/components/ProfileType/ProfileTypeNavigation.spec.tsx b/src/components/ProfileType/ProfileTypeNavigation.spec.tsx index 40b1c941aed6672f04c051c0dc246fdaf7f973ab..43e1d743e726820d65a2f517f4cc0c4f78939eed 100644 --- a/src/components/ProfileType/ProfileTypeNavigation.spec.tsx +++ b/src/components/ProfileType/ProfileTypeNavigation.spec.tsx @@ -5,7 +5,7 @@ import MuiButton from '@material-ui/core/Button' import { createMockStore, mockInitialEcolyoState, -} from '../../../test/__mocks__/store' +} from '../../../tests/__mocks__/store' import ProfileTypeNavigation from './ProfileTypeNavigation' import { ProfileTypeStepForm } from 'enum/profileType.enum' diff --git a/src/components/ProfileType/ProfileTypeView.spec.tsx b/src/components/ProfileType/ProfileTypeView.spec.tsx index 0ee5bbd8895c0b9bd6c6cada99b8934042c19dbb..8bc1460237445aa465f15481260e1b57c212fe8f 100644 --- a/src/components/ProfileType/ProfileTypeView.spec.tsx +++ b/src/components/ProfileType/ProfileTypeView.spec.tsx @@ -1,40 +1,40 @@ -import React from 'react' -import { Provider } from 'react-redux' -import { mount } from 'enzyme' -import ProfileTypeView from 'components/ProfileType/ProfileTypeView' -import CozyBar from 'components/Header/CozyBar' -import Header from 'components/Header/Header' -import Content from 'components/Content/Content' -import { - createMockStore, - mockInitialEcolyoState, -} from '../../../test/__mocks__/store' - -jest.mock('cozy-ui/transpiled/react/I18n', () => { - return { - useI18n: jest.fn(() => { - return { - t: (str: string) => str, - } - }), - } -}) - -describe('ProfileTypeView component', () => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let store: any - beforeEach(() => { - store = createMockStore(mockInitialEcolyoState) - }) - - it('should be rendered correctly', () => { - const wrapper = mount( - <Provider store={store}> - <ProfileTypeView /> - </Provider> - ) - expect(wrapper.find(CozyBar)).toBeTruthy() - expect(wrapper.find(Header)).toBeTruthy() - expect(wrapper.find(Content)).toBeTruthy() - }) -}) +import React from 'react' +import { Provider } from 'react-redux' +import { mount } from 'enzyme' +import ProfileTypeView from 'components/ProfileType/ProfileTypeView' +import CozyBar from 'components/Header/CozyBar' +import Header from 'components/Header/Header' +import Content from 'components/Content/Content' +import { + createMockStore, + mockInitialEcolyoState, +} from '../../../tests/__mocks__/store' + +jest.mock('cozy-ui/transpiled/react/I18n', () => { + return { + useI18n: jest.fn(() => { + return { + t: (str: string) => str, + } + }), + } +}) + +describe('ProfileTypeView component', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let store: any + beforeEach(() => { + store = createMockStore(mockInitialEcolyoState) + }) + + it('should be rendered correctly', () => { + const wrapper = mount( + <Provider store={store}> + <ProfileTypeView /> + </Provider> + ) + expect(wrapper.find(CozyBar)).toBeTruthy() + expect(wrapper.find(Header)).toBeTruthy() + expect(wrapper.find(Content)).toBeTruthy() + }) +}) diff --git a/src/components/Quiz/QuizBegin.spec.tsx b/src/components/Quiz/QuizBegin.spec.tsx index dbf9502b2172b30bae6ebbf17d5e9d3537ff1b65..b7d46a8d7d6883892bb84173fe8498ab72e89108 100644 --- a/src/components/Quiz/QuizBegin.spec.tsx +++ b/src/components/Quiz/QuizBegin.spec.tsx @@ -1,55 +1,55 @@ -import React from 'react' -import { mount } from 'enzyme' -import { Provider } from 'react-redux' -import configureStore from 'redux-mock-store' -import QuizBegin from './QuizBegin' -import { globalStateData } from '../../../test/__mocks__/globalStateData.mock' -import { userChallengeData } from '../../../test/__mocks__/userChallengeData.mock' -import MuiButton from '@material-ui/core/Button' -import StyledIcon from 'components/CommonKit/Icon/StyledIcon' -import { UserChallengeUpdateFlag } from 'enum/userChallenge.enum' - -jest.mock('cozy-ui/transpiled/react/I18n', () => { - return { - useI18n: jest.fn(() => { - return { - t: (str: string) => str, - } - }), - } -}) - -const mockUserChallengeUpdateFlag = jest.fn() -jest.mock('services/challenge.service', () => { - return jest.fn(() => { - return { - updateUserChallenge: mockUserChallengeUpdateFlag, - } - }) -}) - -const mockStore = configureStore([]) - -describe('QuizBegin component', () => { - it('should be rendered correctly', () => { - const store = mockStore({ - ecolyo: { - global: globalStateData, - }, - }) - const wrapper = mount( - <Provider store={store}> - <QuizBegin userChallenge={userChallengeData[0]} /> - </Provider> - ) - expect(wrapper.find(StyledIcon).exists()).toBeTruthy() - wrapper - .find('.button-start') - .find(MuiButton) - .simulate('click') - expect(mockUserChallengeUpdateFlag).toHaveBeenCalledWith( - userChallengeData[0], - UserChallengeUpdateFlag.QUIZ_START - ) - }) -}) +import React from 'react' +import { mount } from 'enzyme' +import { Provider } from 'react-redux' +import configureStore from 'redux-mock-store' +import QuizBegin from './QuizBegin' +import { globalStateData } from '../../../tests/__mocks__/globalStateData.mock' +import { userChallengeData } from '../../../tests/__mocks__/userChallengeData.mock' +import MuiButton from '@material-ui/core/Button' +import StyledIcon from 'components/CommonKit/Icon/StyledIcon' +import { UserChallengeUpdateFlag } from 'enum/userChallenge.enum' + +jest.mock('cozy-ui/transpiled/react/I18n', () => { + return { + useI18n: jest.fn(() => { + return { + t: (str: string) => str, + } + }), + } +}) + +const mockUserChallengeUpdateFlag = jest.fn() +jest.mock('services/challenge.service', () => { + return jest.fn(() => { + return { + updateUserChallenge: mockUserChallengeUpdateFlag, + } + }) +}) + +const mockStore = configureStore([]) + +describe('QuizBegin component', () => { + it('should be rendered correctly', () => { + const store = mockStore({ + ecolyo: { + global: globalStateData, + }, + }) + const wrapper = mount( + <Provider store={store}> + <QuizBegin userChallenge={userChallengeData[0]} /> + </Provider> + ) + expect(wrapper.find(StyledIcon).exists()).toBeTruthy() + wrapper + .find('.button-start') + .find(MuiButton) + .simulate('click') + expect(mockUserChallengeUpdateFlag).toHaveBeenCalledWith( + userChallengeData[0], + UserChallengeUpdateFlag.QUIZ_START + ) + }) +}) diff --git a/src/components/Quiz/QuizCustomQuestionContent.spec.tsx b/src/components/Quiz/QuizCustomQuestionContent.spec.tsx index f951922a53dd547d9e3a5c4dc80f5a1e2d9274fb..0df56a35cce0ee9e6d8cfbf1125394473648ee2e 100644 --- a/src/components/Quiz/QuizCustomQuestionContent.spec.tsx +++ b/src/components/Quiz/QuizCustomQuestionContent.spec.tsx @@ -2,13 +2,13 @@ import React from 'react' import { mount } from 'enzyme' import { Provider } from 'react-redux' import configureStore from 'redux-mock-store' -import { userChallengeData } from '../../../test/__mocks__/userChallengeData.mock' -import { globalStateData } from '../../../test/__mocks__/globalStateData.mock' -import { challengeStateData } from '../../../test/__mocks__/challengeStateData.mock' +import { userChallengeData } from '../../../tests/__mocks__/userChallengeData.mock' +import { globalStateData } from '../../../tests/__mocks__/globalStateData.mock' +import { challengeStateData } from '../../../tests/__mocks__/challengeStateData.mock' import MuiButton from '@material-ui/core/Button' import QuizExplanationModal from './QuizExplanationModal' import QuizCustomQuestionContent from './QuizCustomQuestionContent' -import { questionEntity } from '../../../test/__mocks__/quizData.mock' +import { questionEntity } from '../../../tests/__mocks__/quizData.mock' import StyledSpinner from 'components/CommonKit/Spinner/StyledEcogestureSpinner' jest.mock('cozy-ui/transpiled/react/I18n', () => { diff --git a/src/components/Quiz/QuizFinish.spec.tsx b/src/components/Quiz/QuizFinish.spec.tsx index 26df999e23ef19be63f040b8dee4da909874bfcf..a74dcc54f1bb8d4a0fb4641d3e7f943ecccea8d3 100644 --- a/src/components/Quiz/QuizFinish.spec.tsx +++ b/src/components/Quiz/QuizFinish.spec.tsx @@ -1,69 +1,69 @@ -import React from 'react' -import { mount } from 'enzyme' -import { Provider } from 'react-redux' -import configureStore from 'redux-mock-store' -import QuizFinish from './QuizFinish' -import { globalStateData } from '../../../test/__mocks__/globalStateData.mock' -import { userChallengeData } from '../../../test/__mocks__/userChallengeData.mock' -import MuiButton from '@material-ui/core/Button' -import StyledIcon from 'components/CommonKit/Icon/StyledIcon' -import { UserChallengeUpdateFlag } from 'enum/userChallenge.enum' -import { act } from '@testing-library/react' - -jest.mock('cozy-ui/transpiled/react/I18n', () => { - return { - useI18n: jest.fn(() => { - return { - t: (str: string) => str, - } - }), - } -}) - -const mockUserChallengeUpdateFlag = jest.fn() -jest.mock('services/challenge.service', () => { - return jest.fn(() => { - return { - updateUserChallenge: mockUserChallengeUpdateFlag, - } - }) -}) - -const mockHistoryPush = jest.fn() -jest.mock('react-router-dom', () => ({ - ...jest.requireActual('react-router-dom'), - useHistory: () => ({ - push: mockHistoryPush, - }), -})) - -const mockStore = configureStore([]) - -describe('QuizFinish', () => { - it('should be rendered correctly', async () => { - const store = mockStore({ - ecolyo: { - global: globalStateData, - }, - }) - const wrapper = mount( - <Provider store={store}> - <QuizFinish userChallenge={userChallengeData[0]} /> - </Provider> - ) - expect(wrapper.find(StyledIcon).exists()).toBeTruthy() - wrapper.find(MuiButton).forEach(node => { - node.simulate('click') - }) - expect(mockUserChallengeUpdateFlag).toHaveBeenCalledWith( - userChallengeData[0], - UserChallengeUpdateFlag.QUIZ_RESET - ) - await act(async () => { - await new Promise(resolve => setTimeout(resolve)) - wrapper.update() - }) - - expect(mockHistoryPush).toHaveBeenCalledWith('/challenges') - }) -}) +import React from 'react' +import { mount } from 'enzyme' +import { Provider } from 'react-redux' +import configureStore from 'redux-mock-store' +import QuizFinish from './QuizFinish' +import { globalStateData } from '../../../tests/__mocks__/globalStateData.mock' +import { userChallengeData } from '../../../tests/__mocks__/userChallengeData.mock' +import MuiButton from '@material-ui/core/Button' +import StyledIcon from 'components/CommonKit/Icon/StyledIcon' +import { UserChallengeUpdateFlag } from 'enum/userChallenge.enum' +import { act } from '@testing-library/react' + +jest.mock('cozy-ui/transpiled/react/I18n', () => { + return { + useI18n: jest.fn(() => { + return { + t: (str: string) => str, + } + }), + } +}) + +const mockUserChallengeUpdateFlag = jest.fn() +jest.mock('services/challenge.service', () => { + return jest.fn(() => { + return { + updateUserChallenge: mockUserChallengeUpdateFlag, + } + }) +}) + +const mockHistoryPush = jest.fn() +jest.mock('react-router-dom', () => ({ + ...jest.requireActual('react-router-dom'), + useHistory: () => ({ + push: mockHistoryPush, + }), +})) + +const mockStore = configureStore([]) + +describe('QuizFinish', () => { + it('should be rendered correctly', async () => { + const store = mockStore({ + ecolyo: { + global: globalStateData, + }, + }) + const wrapper = mount( + <Provider store={store}> + <QuizFinish userChallenge={userChallengeData[0]} /> + </Provider> + ) + expect(wrapper.find(StyledIcon).exists()).toBeTruthy() + wrapper.find(MuiButton).forEach(node => { + node.simulate('click') + }) + expect(mockUserChallengeUpdateFlag).toHaveBeenCalledWith( + userChallengeData[0], + UserChallengeUpdateFlag.QUIZ_RESET + ) + await act(async () => { + await new Promise(resolve => setTimeout(resolve)) + wrapper.update() + }) + + expect(mockHistoryPush).toHaveBeenCalledWith('/challenges') + }) +}) diff --git a/src/components/Quiz/QuizQuestion.spec.tsx b/src/components/Quiz/QuizQuestion.spec.tsx index d6770e6b129cf0e4ba068ff6e4a1ca4986822bea..240eefd26fa0dfb0c99634056c194037aac92890 100644 --- a/src/components/Quiz/QuizQuestion.spec.tsx +++ b/src/components/Quiz/QuizQuestion.spec.tsx @@ -6,9 +6,9 @@ import * as reactRedux from 'react-redux' import { createMockStore, mockInitialEcolyoState, -} from '../../../test/__mocks__/store' +} from '../../../tests/__mocks__/store' import QuizQuestion from './QuizQuestion' -import { userChallengeData } from '../../../test/__mocks__/userChallengeData.mock' +import { userChallengeData } from '../../../tests/__mocks__/userChallengeData.mock' import { UserQuestionState } from 'enum/userQuiz.enum' jest.mock('cozy-ui/transpiled/react/I18n', () => { diff --git a/src/components/Quiz/QuizQuestionContent.spec.tsx b/src/components/Quiz/QuizQuestionContent.spec.tsx index f1cc9ca9ffc48563c6497aa505d8c88dcb5145f8..f443f7554c6f407f9796426952ca2c0e5b5afa5d 100644 --- a/src/components/Quiz/QuizQuestionContent.spec.tsx +++ b/src/components/Quiz/QuizQuestionContent.spec.tsx @@ -1,93 +1,93 @@ -import React from 'react' -import { mount } from 'enzyme' -import { Provider } from 'react-redux' -import configureStore from 'redux-mock-store' -import { userChallengeData } from '../../../test/__mocks__/userChallengeData.mock' -import { globalStateData } from '../../../test/__mocks__/globalStateData.mock' -import { challengeStateData } from '../../../test/__mocks__/challengeStateData.mock' -import QuizQuestionContent from 'components/Quiz/QuizQuestionContent' - -jest.mock('cozy-ui/transpiled/react/I18n', () => { - return { - useI18n: jest.fn(() => { - return { - t: (str: string) => str, - } - }), - } -}) - -const mockHistoryPush = jest.fn() -jest.mock('react-router-dom', () => ({ - ...jest.requireActual('react-router-dom'), - useHistory: () => ({ - push: mockHistoryPush, - }), -})) - -const mockUpdateUserQuiz = jest.fn() -jest.mock('services/quiz.service', () => { - return jest.fn(() => { - return { - updateUserQuiz: mockUpdateUserQuiz, - } - }) -}) - -const mockUserChallengeUpdateFlag = jest.fn() -jest.mock('services/challenge.service', () => { - return jest.fn(() => { - return { - updateUserChallenge: mockUserChallengeUpdateFlag, - } - }) -}) - -const mockStore = configureStore([]) - -describe('QuizQuestionContent component', () => { - it('should be rendered correctly', () => { - const store = mockStore({ - ecolyo: { - global: globalStateData, - challenge: challengeStateData, - }, - }) - const wrapper = mount( - <Provider store={store}> - <QuizQuestionContent - userChallenge={userChallengeData[0]} - setIsCustomQuest={() => false} - goBack={mockHistoryPush('/challenges')} - /> - </Provider> - ) - expect(wrapper.find('.question').text()).toEqual( - userChallengeData[0].quiz.questions[0].questionLabel - ) - expect(wrapper.find('input')).toHaveLength(3) - }) - it('should redirect to challenge on click on btn-back', () => { - const store = mockStore({ - ecolyo: { - global: globalStateData, - challenge: challengeStateData, - }, - }) - const wrapper = mount( - <Provider store={store}> - <QuizQuestionContent - userChallenge={userChallengeData[0]} - setIsCustomQuest={() => false} - goBack={mockHistoryPush('/challenges')} - /> - </Provider> - ) - - wrapper - .find('.btn-back') - .first() - .simulate('click') - expect(mockHistoryPush).toHaveBeenCalledWith('/challenges') - }) -}) +import React from 'react' +import { mount } from 'enzyme' +import { Provider } from 'react-redux' +import configureStore from 'redux-mock-store' +import { userChallengeData } from '../../../tests/__mocks__/userChallengeData.mock' +import { globalStateData } from '../../../tests/__mocks__/globalStateData.mock' +import { challengeStateData } from '../../../tests/__mocks__/challengeStateData.mock' +import QuizQuestionContent from 'components/Quiz/QuizQuestionContent' + +jest.mock('cozy-ui/transpiled/react/I18n', () => { + return { + useI18n: jest.fn(() => { + return { + t: (str: string) => str, + } + }), + } +}) + +const mockHistoryPush = jest.fn() +jest.mock('react-router-dom', () => ({ + ...jest.requireActual('react-router-dom'), + useHistory: () => ({ + push: mockHistoryPush, + }), +})) + +const mockUpdateUserQuiz = jest.fn() +jest.mock('services/quiz.service', () => { + return jest.fn(() => { + return { + updateUserQuiz: mockUpdateUserQuiz, + } + }) +}) + +const mockUserChallengeUpdateFlag = jest.fn() +jest.mock('services/challenge.service', () => { + return jest.fn(() => { + return { + updateUserChallenge: mockUserChallengeUpdateFlag, + } + }) +}) + +const mockStore = configureStore([]) + +describe('QuizQuestionContent component', () => { + it('should be rendered correctly', () => { + const store = mockStore({ + ecolyo: { + global: globalStateData, + challenge: challengeStateData, + }, + }) + const wrapper = mount( + <Provider store={store}> + <QuizQuestionContent + userChallenge={userChallengeData[0]} + setIsCustomQuest={() => false} + goBack={mockHistoryPush('/challenges')} + /> + </Provider> + ) + expect(wrapper.find('.question').text()).toEqual( + userChallengeData[0].quiz.questions[0].questionLabel + ) + expect(wrapper.find('input')).toHaveLength(3) + }) + it('should redirect to challenge on click on btn-back', () => { + const store = mockStore({ + ecolyo: { + global: globalStateData, + challenge: challengeStateData, + }, + }) + const wrapper = mount( + <Provider store={store}> + <QuizQuestionContent + userChallenge={userChallengeData[0]} + setIsCustomQuest={() => false} + goBack={mockHistoryPush('/challenges')} + /> + </Provider> + ) + + wrapper + .find('.btn-back') + .first() + .simulate('click') + expect(mockHistoryPush).toHaveBeenCalledWith('/challenges') + }) +}) diff --git a/src/components/Quiz/QuizView.spec.tsx b/src/components/Quiz/QuizView.spec.tsx index 6f59c9b40c9320126ffe81086ced36056cbe6a3b..788a3fe499b68a9c211c1af83ea4a0db598ee6f2 100644 --- a/src/components/Quiz/QuizView.spec.tsx +++ b/src/components/Quiz/QuizView.spec.tsx @@ -1,70 +1,70 @@ -import React from 'react' -import { shallow } from 'enzyme' -import QuizView from 'components/Quiz/QuizView' -import * as reactRedux from 'react-redux' -import { UserQuizState } from 'enum/userQuiz.enum' -import { challengeStateData } from '../../../test/__mocks__/challengeStateData.mock' -import { userChallengeData } from '../../../test/__mocks__/userChallengeData.mock' -import QuizBegin from './QuizBegin' -import QuizQuestion from './QuizQuestion' -import QuizFinish from './QuizFinish' - -const mockUseSelector = jest.spyOn(reactRedux, 'useSelector') - -describe('QuizView component', () => { - it('should be rendered with QuizBegin component when quiz state = unlocked', () => { - const updatedUserChallenge = { - ...userChallengeData[0], - quiz: { ...userChallengeData[0].quiz, state: UserQuizState.UNLOCKED }, - } - const updatedChallengeState = { - ...challengeStateData, - currentChallenge: updatedUserChallenge, - } - mockUseSelector.mockReturnValue(updatedChallengeState) - const wrapper = shallow(<QuizView />) - expect(wrapper.find(QuizBegin).exists()) - }) - - it('should be rendered with QuizQuestion component when quiz state = ongoing', () => { - const updatedUserChallenge = { - ...userChallengeData[0], - quiz: { ...userChallengeData[0].quiz, state: UserQuizState.ONGOING }, - } - const updatedChallengeState = { - ...challengeStateData, - currentChallenge: updatedUserChallenge, - } - mockUseSelector.mockReturnValue(updatedChallengeState) - const wrapper = shallow(<QuizView />) - expect(wrapper.find(QuizQuestion).exists()) - }) - - it('should be rendered with QuizFinish component when quiz state = done', () => { - const updatedUserChallenge = { - ...userChallengeData[0], - quiz: { ...userChallengeData[0].quiz, state: UserQuizState.DONE }, - } - const updatedChallengeState = { - ...challengeStateData, - currentChallenge: updatedUserChallenge, - } - mockUseSelector.mockReturnValue(updatedChallengeState) - const wrapper = shallow(<QuizView />) - expect(wrapper.find(QuizFinish).exists()) - }) - - it('should be rendered with QuizBegin component when quiz state = null', () => { - const updatedUserChallenge = { - ...userChallengeData[0], - quiz: { ...userChallengeData[0].quiz, state: null }, - } - const updatedChallengeState = { - ...challengeStateData, - currentChallenge: updatedUserChallenge, - } - mockUseSelector.mockReturnValue(updatedChallengeState) - const wrapper = shallow(<QuizView />) - expect(wrapper.find(QuizBegin).exists()) - }) -}) +import React from 'react' +import { shallow } from 'enzyme' +import QuizView from 'components/Quiz/QuizView' +import * as reactRedux from 'react-redux' +import { UserQuizState } from 'enum/userQuiz.enum' +import { challengeStateData } from '../../../tests/__mocks__/challengeStateData.mock' +import { userChallengeData } from '../../../tests/__mocks__/userChallengeData.mock' +import QuizBegin from './QuizBegin' +import QuizQuestion from './QuizQuestion' +import QuizFinish from './QuizFinish' + +const mockUseSelector = jest.spyOn(reactRedux, 'useSelector') + +describe('QuizView component', () => { + it('should be rendered with QuizBegin component when quiz state = unlocked', () => { + const updatedUserChallenge = { + ...userChallengeData[0], + quiz: { ...userChallengeData[0].quiz, state: UserQuizState.UNLOCKED }, + } + const updatedChallengeState = { + ...challengeStateData, + currentChallenge: updatedUserChallenge, + } + mockUseSelector.mockReturnValue(updatedChallengeState) + const wrapper = shallow(<QuizView />) + expect(wrapper.find(QuizBegin).exists()) + }) + + it('should be rendered with QuizQuestion component when quiz state = ongoing', () => { + const updatedUserChallenge = { + ...userChallengeData[0], + quiz: { ...userChallengeData[0].quiz, state: UserQuizState.ONGOING }, + } + const updatedChallengeState = { + ...challengeStateData, + currentChallenge: updatedUserChallenge, + } + mockUseSelector.mockReturnValue(updatedChallengeState) + const wrapper = shallow(<QuizView />) + expect(wrapper.find(QuizQuestion).exists()) + }) + + it('should be rendered with QuizFinish component when quiz state = done', () => { + const updatedUserChallenge = { + ...userChallengeData[0], + quiz: { ...userChallengeData[0].quiz, state: UserQuizState.DONE }, + } + const updatedChallengeState = { + ...challengeStateData, + currentChallenge: updatedUserChallenge, + } + mockUseSelector.mockReturnValue(updatedChallengeState) + const wrapper = shallow(<QuizView />) + expect(wrapper.find(QuizFinish).exists()) + }) + + it('should be rendered with QuizBegin component when quiz state = null', () => { + const updatedUserChallenge = { + ...userChallengeData[0], + quiz: { ...userChallengeData[0].quiz, state: null }, + } + const updatedChallengeState = { + ...challengeStateData, + currentChallenge: updatedUserChallenge, + } + mockUseSelector.mockReturnValue(updatedChallengeState) + const wrapper = shallow(<QuizView />) + expect(wrapper.find(QuizBegin).exists()) + }) +}) diff --git a/src/components/SingleFluid/SingleFluidView.spec.tsx b/src/components/SingleFluid/SingleFluidView.spec.tsx index 9e37011e0bc548c07527244d5429103e8e15b275..2960395d15ea027933101b94314f5c2fac90be61 100644 --- a/src/components/SingleFluid/SingleFluidView.spec.tsx +++ b/src/components/SingleFluid/SingleFluidView.spec.tsx @@ -1,96 +1,96 @@ -/* eslint-disable react/display-name */ -import React from 'react' -import { mount } from 'enzyme' -import { Provider } from 'react-redux' -import * as reactRedux from 'react-redux' -import { - createMockStore, - mockInitialEcolyoState, -} from '../../../test/__mocks__/store' -import * as chartActions from 'store/chart/chart.actions' -import SingleFluidView from 'components/SingleFluid/SingleFluidView' -import { FluidType } from 'enum/fluid.enum' -import { TimeStep } from 'enum/timeStep.enum' -import StyledSpinner from 'components/CommonKit/Spinner/StyledSpinner' - -jest.mock('cozy-ui/transpiled/react/I18n', () => { - return { - useI18n: jest.fn(() => { - return { - t: (str: string) => str, - } - }), - } -}) -jest.mock('components/Header/CozyBar', () => () => <div id="cozybar"></div>) -jest.mock('components/Header/Header', () => () => <div id="header"></div>) -jest.mock('components/DateNavigator/DateNavigator', () => () => ( - <div id="datenavigator"></div> -)) -jest.mock('components/FluidChart/FluidChart', () => () => ( - <div id="fluidchart"></div> -)) -jest.mock('components/Home/ConsumptionDetails', () => () => ( - <div id="consumptiondetails"></div> -)) - -const useSelectorSpy = jest.spyOn(reactRedux, 'useSelector') -const useDispatchSpy = jest.spyOn(reactRedux, 'useDispatch') -const setCurrentTimeStepSpy = jest.spyOn(chartActions, 'setCurrentTimeStep') - -describe('SingleFluidView component', () => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let store: any - beforeEach(() => { - store = createMockStore(mockInitialEcolyoState) - useDispatchSpy.mockClear() - setCurrentTimeStepSpy.mockClear() - }) - - it('should be rendered correctly', () => { - useSelectorSpy.mockReturnValue({ - currentTimeStep: TimeStep.WEEK, - loading: false, - }) - const wrapper = mount( - <Provider store={store}> - <SingleFluidView fluidType={FluidType.ELECTRICITY} /> - </Provider> - ) - expect(wrapper.find('#cozybar')).toBeTruthy() - expect(wrapper.find('#header')).toBeTruthy() - expect(wrapper.find('#datenavigator')).toBeTruthy() - expect(wrapper.find('#fluidchart')).toBeTruthy() - expect(wrapper.find('#consumptiondetails')).toBeTruthy() - }) - - it('should display a spinner', () => { - useSelectorSpy.mockReturnValue({ - currentTimeStep: TimeStep.WEEK, - loading: true, - }) - const wrapper = mount( - <Provider store={store}> - <SingleFluidView fluidType={FluidType.ELECTRICITY} /> - </Provider> - ) - expect(wrapper.find('#cozybar')).toBeTruthy() - expect(wrapper.find('#header')).toBeTruthy() - expect(wrapper.find('#datenavigator')).toBeTruthy() - expect(wrapper.find(StyledSpinner)).toBeTruthy() - }) - - it('should set CurrentTimeStep to WEEK when fluid != ELECTRICITY and timeStep = HALF_AN_HOUR', () => { - useSelectorSpy.mockReturnValue({ - currentTimeStep: TimeStep.HALF_AN_HOUR, - loading: true, - }) - mount( - <Provider store={store}> - <SingleFluidView fluidType={FluidType.GAS} /> - </Provider> - ) - expect(setCurrentTimeStepSpy).toBeCalledTimes(1) - expect(setCurrentTimeStepSpy).toHaveBeenCalledWith(TimeStep.WEEK) - }) -}) +/* eslint-disable react/display-name */ +import React from 'react' +import { mount } from 'enzyme' +import { Provider } from 'react-redux' +import * as reactRedux from 'react-redux' +import { + createMockStore, + mockInitialEcolyoState, +} from '../../../tests/__mocks__/store' +import * as chartActions from 'store/chart/chart.actions' +import SingleFluidView from 'components/SingleFluid/SingleFluidView' +import { FluidType } from 'enum/fluid.enum' +import { TimeStep } from 'enum/timeStep.enum' +import StyledSpinner from 'components/CommonKit/Spinner/StyledSpinner' + +jest.mock('cozy-ui/transpiled/react/I18n', () => { + return { + useI18n: jest.fn(() => { + return { + t: (str: string) => str, + } + }), + } +}) +jest.mock('components/Header/CozyBar', () => () => <div id="cozybar"></div>) +jest.mock('components/Header/Header', () => () => <div id="header"></div>) +jest.mock('components/DateNavigator/DateNavigator', () => () => ( + <div id="datenavigator"></div> +)) +jest.mock('components/FluidChart/FluidChart', () => () => ( + <div id="fluidchart"></div> +)) +jest.mock('components/Home/ConsumptionDetails', () => () => ( + <div id="consumptiondetails"></div> +)) + +const useSelectorSpy = jest.spyOn(reactRedux, 'useSelector') +const useDispatchSpy = jest.spyOn(reactRedux, 'useDispatch') +const setCurrentTimeStepSpy = jest.spyOn(chartActions, 'setCurrentTimeStep') + +describe('SingleFluidView component', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let store: any + beforeEach(() => { + store = createMockStore(mockInitialEcolyoState) + useDispatchSpy.mockClear() + setCurrentTimeStepSpy.mockClear() + }) + + it('should be rendered correctly', () => { + useSelectorSpy.mockReturnValue({ + currentTimeStep: TimeStep.WEEK, + loading: false, + }) + const wrapper = mount( + <Provider store={store}> + <SingleFluidView fluidType={FluidType.ELECTRICITY} /> + </Provider> + ) + expect(wrapper.find('#cozybar')).toBeTruthy() + expect(wrapper.find('#header')).toBeTruthy() + expect(wrapper.find('#datenavigator')).toBeTruthy() + expect(wrapper.find('#fluidchart')).toBeTruthy() + expect(wrapper.find('#consumptiondetails')).toBeTruthy() + }) + + it('should display a spinner', () => { + useSelectorSpy.mockReturnValue({ + currentTimeStep: TimeStep.WEEK, + loading: true, + }) + const wrapper = mount( + <Provider store={store}> + <SingleFluidView fluidType={FluidType.ELECTRICITY} /> + </Provider> + ) + expect(wrapper.find('#cozybar')).toBeTruthy() + expect(wrapper.find('#header')).toBeTruthy() + expect(wrapper.find('#datenavigator')).toBeTruthy() + expect(wrapper.find(StyledSpinner)).toBeTruthy() + }) + + it('should set CurrentTimeStep to WEEK when fluid != ELECTRICITY and timeStep = HALF_AN_HOUR', () => { + useSelectorSpy.mockReturnValue({ + currentTimeStep: TimeStep.HALF_AN_HOUR, + loading: true, + }) + mount( + <Provider store={store}> + <SingleFluidView fluidType={FluidType.GAS} /> + </Provider> + ) + expect(setCurrentTimeStepSpy).toBeCalledTimes(1) + expect(setCurrentTimeStepSpy).toHaveBeenCalledWith(TimeStep.WEEK) + }) +}) diff --git a/src/components/Splash/SplashRoot.spec.tsx b/src/components/Splash/SplashRoot.spec.tsx index 29487426dd204e96565b193ed2873d5d5a02ab18..c8da7353f415908be3022cabb34fd1a588a508c0 100644 --- a/src/components/Splash/SplashRoot.spec.tsx +++ b/src/components/Splash/SplashRoot.spec.tsx @@ -1,26 +1,26 @@ -import React from 'react' -import { shallow } from 'enzyme' -import SplashRoot from './SplashRoot' -import * as reactRedux from 'react-redux' -import SplashScreen from './SplashScreen' -import SplashScreenError from './SplashScreenError' -import { userChallengeExplo1OnGoing } from '../../../test/__mocks__/userChallengeData.mock' - -const mockUseSelector = jest.spyOn(reactRedux, 'useSelector') -const mockUseDispatch = jest.spyOn(reactRedux, 'useDispatch') - -describe('SplashRoot component', () => { - it('should be rendered correctly', () => { - mockUseSelector.mockReturnValue(userChallengeExplo1OnGoing) - mockUseDispatch.mockReturnValue(jest.fn()) - const component = shallow( - <SplashRoot - splashComponent={SplashScreen} - splashErrorComponent={SplashScreenError} - > - children - </SplashRoot> - ).getElement() - expect(component).toMatchSnapshot() - }) -}) +import React from 'react' +import { shallow } from 'enzyme' +import SplashRoot from './SplashRoot' +import * as reactRedux from 'react-redux' +import SplashScreen from './SplashScreen' +import SplashScreenError from './SplashScreenError' +import { userChallengeExplo1OnGoing } from '../../../tests/__mocks__/userChallengeData.mock' + +const mockUseSelector = jest.spyOn(reactRedux, 'useSelector') +const mockUseDispatch = jest.spyOn(reactRedux, 'useDispatch') + +describe('SplashRoot component', () => { + it('should be rendered correctly', () => { + mockUseSelector.mockReturnValue(userChallengeExplo1OnGoing) + mockUseDispatch.mockReturnValue(jest.fn()) + const component = shallow( + <SplashRoot + splashComponent={SplashScreen} + splashErrorComponent={SplashScreenError} + > + children + </SplashRoot> + ).getElement() + expect(component).toMatchSnapshot() + }) +}) diff --git a/src/components/TimeStepSelector/TimeStepSelector.spec.tsx b/src/components/TimeStepSelector/TimeStepSelector.spec.tsx index d9081d89a11800c76e1a62949df5b38faf9e9ab2..66b8364a4fec088d538a7ed99af23d01c92e9d56 100644 --- a/src/components/TimeStepSelector/TimeStepSelector.spec.tsx +++ b/src/components/TimeStepSelector/TimeStepSelector.spec.tsx @@ -1,156 +1,156 @@ -import React from 'react' -import { mount } from 'enzyme' -import { Provider } from 'react-redux' -import * as reactRedux from 'react-redux' -import TimeStepSelector from 'components/TimeStepSelector/TimeStepSelector' -import { - createMockStore, - mockInitialEcolyoState, -} from '../../../test/__mocks__/store' -import * as chartActions from 'store/chart/chart.actions' -import { FluidType } from 'enum/fluid.enum' -import { TimeStep } from 'enum/timeStep.enum' -import { DateTime } from 'luxon' - -jest.mock('cozy-ui/transpiled/react/I18n', () => { - return { - useI18n: jest.fn(() => { - return { - t: (str: string) => str, - } - }), - } -}) - -const useSelectorSpy = jest.spyOn(reactRedux, 'useSelector') -const useDispatchSpy = jest.spyOn(reactRedux, 'useDispatch') -const setCurrentTimeStepSpy = jest.spyOn(chartActions, 'setCurrentTimeStep') - -describe('TimeStepSelector component', () => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let store: any - beforeEach(() => { - store = createMockStore(mockInitialEcolyoState) - useSelectorSpy.mockClear() - useDispatchSpy.mockClear() - setCurrentTimeStepSpy.mockClear() - }) - - it('should be rendered with 2 inputs', () => { - const wrapper = mount( - <Provider store={store}> - <TimeStepSelector fluidType={FluidType.ELECTRICITY} /> - </Provider> - ) - expect(wrapper.find('button')).toHaveLength(2) - }) - - it('should disable the zoom in button when TimeStep is HALF_AN_HOUR and fluid is ELECTRICITY', () => { - useSelectorSpy.mockReturnValueOnce({ - currentTimeStep: TimeStep.HALF_AN_HOUR, - }) - const wrapper = mount( - <Provider store={store}> - <TimeStepSelector fluidType={FluidType.ELECTRICITY} /> - </Provider> - ) - expect( - wrapper - .find('button') - .first() - .prop('disabled') - ).toBe(true) - expect( - wrapper - .find('button') - .last() - .prop('disabled') - ).toBe(false) - }) - - it('should disable the zoom in button when TimeStep is WEEK and fluid is not ELECTRICITY', () => { - useSelectorSpy.mockReturnValueOnce({ - currentTimeStep: TimeStep.WEEK, - }) - const wrapper = mount( - <Provider store={store}> - <TimeStepSelector fluidType={FluidType.GAS} /> - </Provider> - ) - expect( - wrapper - .find('button') - .first() - .prop('disabled') - ).toBe(true) - expect( - wrapper - .find('button') - .last() - .prop('disabled') - ).toBe(false) - }) - - it('should disable the zoom out button when TimeStep is YEAR', () => { - useSelectorSpy.mockReturnValueOnce({ - currentTimeStep: TimeStep.YEAR, - }) - const wrapper = mount( - <Provider store={store}> - <TimeStepSelector fluidType={FluidType.ELECTRICITY} /> - </Provider> - ) - expect( - wrapper - .find('button') - .first() - .prop('disabled') - ).toBe(false) - expect( - wrapper - .find('button') - .last() - .prop('disabled') - ).toBe(true) - }) - - it('should define previous TimeStep and dispatch it', () => { - useSelectorSpy.mockReturnValue({ - currentTimeStep: TimeStep.DAY, - selectedDate: DateTime.local().setZone('utc', { - keepLocalTime: true, - }), - }) - const wrapper = mount( - <Provider store={store}> - <TimeStepSelector fluidType={FluidType.ELECTRICITY} /> - </Provider> - ) - wrapper - .find('button') - .first() - .simulate('click') - expect(setCurrentTimeStepSpy).toBeCalledTimes(1) - expect(setCurrentTimeStepSpy).toHaveBeenCalledWith(TimeStep.WEEK) - }) - - it('should define next TimeStep and dispatch it', () => { - useSelectorSpy.mockReturnValue({ - currentTimeStep: TimeStep.DAY, - selectedDate: DateTime.local().setZone('utc', { - keepLocalTime: true, - }), - }) - const wrapper = mount( - <Provider store={store}> - <TimeStepSelector fluidType={FluidType.ELECTRICITY} /> - </Provider> - ) - wrapper - .find('button') - .last() - .simulate('click') - expect(setCurrentTimeStepSpy).toBeCalledTimes(1) - expect(setCurrentTimeStepSpy).toHaveBeenCalledWith(TimeStep.MONTH) - }) -}) +import React from 'react' +import { mount } from 'enzyme' +import { Provider } from 'react-redux' +import * as reactRedux from 'react-redux' +import TimeStepSelector from 'components/TimeStepSelector/TimeStepSelector' +import { + createMockStore, + mockInitialEcolyoState, +} from '../../../tests/__mocks__/store' +import * as chartActions from 'store/chart/chart.actions' +import { FluidType } from 'enum/fluid.enum' +import { TimeStep } from 'enum/timeStep.enum' +import { DateTime } from 'luxon' + +jest.mock('cozy-ui/transpiled/react/I18n', () => { + return { + useI18n: jest.fn(() => { + return { + t: (str: string) => str, + } + }), + } +}) + +const useSelectorSpy = jest.spyOn(reactRedux, 'useSelector') +const useDispatchSpy = jest.spyOn(reactRedux, 'useDispatch') +const setCurrentTimeStepSpy = jest.spyOn(chartActions, 'setCurrentTimeStep') + +describe('TimeStepSelector component', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let store: any + beforeEach(() => { + store = createMockStore(mockInitialEcolyoState) + useSelectorSpy.mockClear() + useDispatchSpy.mockClear() + setCurrentTimeStepSpy.mockClear() + }) + + it('should be rendered with 2 inputs', () => { + const wrapper = mount( + <Provider store={store}> + <TimeStepSelector fluidType={FluidType.ELECTRICITY} /> + </Provider> + ) + expect(wrapper.find('button')).toHaveLength(2) + }) + + it('should disable the zoom in button when TimeStep is HALF_AN_HOUR and fluid is ELECTRICITY', () => { + useSelectorSpy.mockReturnValueOnce({ + currentTimeStep: TimeStep.HALF_AN_HOUR, + }) + const wrapper = mount( + <Provider store={store}> + <TimeStepSelector fluidType={FluidType.ELECTRICITY} /> + </Provider> + ) + expect( + wrapper + .find('button') + .first() + .prop('disabled') + ).toBe(true) + expect( + wrapper + .find('button') + .last() + .prop('disabled') + ).toBe(false) + }) + + it('should disable the zoom in button when TimeStep is WEEK and fluid is not ELECTRICITY', () => { + useSelectorSpy.mockReturnValueOnce({ + currentTimeStep: TimeStep.WEEK, + }) + const wrapper = mount( + <Provider store={store}> + <TimeStepSelector fluidType={FluidType.GAS} /> + </Provider> + ) + expect( + wrapper + .find('button') + .first() + .prop('disabled') + ).toBe(true) + expect( + wrapper + .find('button') + .last() + .prop('disabled') + ).toBe(false) + }) + + it('should disable the zoom out button when TimeStep is YEAR', () => { + useSelectorSpy.mockReturnValueOnce({ + currentTimeStep: TimeStep.YEAR, + }) + const wrapper = mount( + <Provider store={store}> + <TimeStepSelector fluidType={FluidType.ELECTRICITY} /> + </Provider> + ) + expect( + wrapper + .find('button') + .first() + .prop('disabled') + ).toBe(false) + expect( + wrapper + .find('button') + .last() + .prop('disabled') + ).toBe(true) + }) + + it('should define previous TimeStep and dispatch it', () => { + useSelectorSpy.mockReturnValue({ + currentTimeStep: TimeStep.DAY, + selectedDate: DateTime.local().setZone('utc', { + keepLocalTime: true, + }), + }) + const wrapper = mount( + <Provider store={store}> + <TimeStepSelector fluidType={FluidType.ELECTRICITY} /> + </Provider> + ) + wrapper + .find('button') + .first() + .simulate('click') + expect(setCurrentTimeStepSpy).toBeCalledTimes(1) + expect(setCurrentTimeStepSpy).toHaveBeenCalledWith(TimeStep.WEEK) + }) + + it('should define next TimeStep and dispatch it', () => { + useSelectorSpy.mockReturnValue({ + currentTimeStep: TimeStep.DAY, + selectedDate: DateTime.local().setZone('utc', { + keepLocalTime: true, + }), + }) + const wrapper = mount( + <Provider store={store}> + <TimeStepSelector fluidType={FluidType.ELECTRICITY} /> + </Provider> + ) + wrapper + .find('button') + .last() + .simulate('click') + expect(setCurrentTimeStepSpy).toBeCalledTimes(1) + expect(setCurrentTimeStepSpy).toHaveBeenCalledWith(TimeStep.MONTH) + }) +}) diff --git a/src/services/account.service.spec.ts b/src/services/account.service.spec.ts index 3f854522b62ecc71835620601c42066756d34f7f..8b7b20c92c0d801afdce927308afcd192e56cd31 100644 --- a/src/services/account.service.spec.ts +++ b/src/services/account.service.spec.ts @@ -1,126 +1,126 @@ -import { QueryResult } from 'cozy-client' -import { AccountAuthData, Account } from 'models' -import mockClient from '../../test/__mocks__/client' -import AccountService from './account.service' -import { accountsData } from '../../test/__mocks__/accountsData.mock' -import { konnectorsData } from '../../test/__mocks__/konnectorsData.mock' - -jest.mock('cozy-harvest-lib/dist/connections/accounts') -import * as harvestLibAccounts from 'cozy-harvest-lib/dist/connections/accounts' -const mockHavestLibAccounts = harvestLibAccounts as jest.Mocked< - typeof harvestLibAccounts -> - -describe('Account service', () => { - const accountService = new AccountService(mockClient) - - describe('createAccount method', () => { - it('should return created account for login type', async () => { - mockHavestLibAccounts.createAccount.mockResolvedValueOnce(accountsData[2]) - const mockAuthData: AccountAuthData = { - login: 'login', - password: 'password', //NOSONAR - } - const result = await accountService.createAccount( - konnectorsData[2], - mockAuthData - ) - expect(result).toEqual(accountsData[2]) - }) - }) - - describe('getAccount method', () => { - it('should return account', async () => { - mockHavestLibAccounts.fetchAccount.mockResolvedValueOnce(accountsData[2]) - const mockId = 'io.cozy.konnectors/eglgrandlyon' - const result = await accountService.getAccount(mockId) - expect(result).toBe(accountsData[2]) - }) - - it('should throw error when fetchAccount unsuccessfully', async () => { - mockHavestLibAccounts.fetchAccount.mockRejectedValueOnce(new Error()) - const mockId = 'io.cozy.konnectors/eglgrandlyon' - try { - await accountService.getAccount(mockId) - } catch (error) { - expect(error).toEqual(new Error('Get account failed')) - } - }) - }) - - describe('getAccountByType method', () => { - it('should return account with account_type equals to eglgrandlyon', async () => { - const mockQueryResult: QueryResult<Account[]> = { - data: [accountsData[2]], - bookmark: '', - next: false, - skip: 0, - } - mockClient.query.mockResolvedValueOnce(mockQueryResult) - const mockType = 'eglgrandlyon' - const result = await accountService.getAccountByType(mockType) - expect(result).toEqual(accountsData[2]) - }) - - it('should return null when no account find', async () => { - const mockQueryResult: QueryResult<Account[]> = { - data: [], - bookmark: '', - next: false, - skip: 0, - } - mockClient.query.mockResolvedValueOnce(mockQueryResult) - const mockType = 'eglgrandlyon' - const result = await accountService.getAccountByType(mockType) - expect(result).toBe(null) - }) - }) - - describe('updateAccount method', () => { - it('should return updated account when updateAccount successfully', async () => { - mockHavestLibAccounts.updateAccount.mockResolvedValueOnce(accountsData[2]) - const result = await accountService.updateAccount(accountsData[2]) - expect(result).toEqual(accountsData[2]) - }) - - it('should throw error when updateAccount unsuccessfully', async () => { - mockHavestLibAccounts.updateAccount.mockRejectedValueOnce(new Error()) - try { - await accountService.updateAccount(accountsData[2]) - } catch (error) { - expect(error).toEqual(new Error('Update account failed')) - } - }) - }) - - describe('deleteAccount method', () => { - it('should return true when destroy successfully', async () => { - mockHavestLibAccounts.deleteAccount.mockResolvedValueOnce(accountsData[2]) - const result = await accountService.deleteAccount(accountsData[2]) - expect(result).toBe(true) - }) - - it('should throw error when destroy unsuccessfully', async () => { - mockHavestLibAccounts.deleteAccount.mockRejectedValueOnce(new Error()) - try { - await accountService.deleteAccount(accountsData[2]) - } catch (error) { - expect(error).toEqual(new Error('Delete account failed')) - } - }) - }) - - describe('createIndexAccount method', () => { - it('should return empty array', async () => { - const mockQueryResult: QueryResult<Account[]> = { - data: [], - bookmark: '', - next: false, - skip: 0, - } - mockClient.query.mockResolvedValueOnce(mockQueryResult) - const result = await accountService.createIndexAccount() - expect(result).toEqual([]) - }) - }) -}) +import { QueryResult } from 'cozy-client' +import { AccountAuthData, Account } from 'models' +import mockClient from '../../tests/__mocks__/client' +import AccountService from './account.service' +import { accountsData } from '../../tests/__mocks__/accountsData.mock' +import { konnectorsData } from '../../tests/__mocks__/konnectorsData.mock' + +jest.mock('cozy-harvest-lib/dist/connections/accounts') +import * as harvestLibAccounts from 'cozy-harvest-lib/dist/connections/accounts' +const mockHavestLibAccounts = harvestLibAccounts as jest.Mocked< + typeof harvestLibAccounts +> + +describe('Account service', () => { + const accountService = new AccountService(mockClient) + + describe('createAccount method', () => { + it('should return created account for login type', async () => { + mockHavestLibAccounts.createAccount.mockResolvedValueOnce(accountsData[2]) + const mockAuthData: AccountAuthData = { + login: 'login', + password: 'password', //NOSONAR + } + const result = await accountService.createAccount( + konnectorsData[2], + mockAuthData + ) + expect(result).toEqual(accountsData[2]) + }) + }) + + describe('getAccount method', () => { + it('should return account', async () => { + mockHavestLibAccounts.fetchAccount.mockResolvedValueOnce(accountsData[2]) + const mockId = 'io.cozy.konnectors/eglgrandlyon' + const result = await accountService.getAccount(mockId) + expect(result).toBe(accountsData[2]) + }) + + it('should throw error when fetchAccount unsuccessfully', async () => { + mockHavestLibAccounts.fetchAccount.mockRejectedValueOnce(new Error()) + const mockId = 'io.cozy.konnectors/eglgrandlyon' + try { + await accountService.getAccount(mockId) + } catch (error) { + expect(error).toEqual(new Error('Get account failed')) + } + }) + }) + + describe('getAccountByType method', () => { + it('should return account with account_type equals to eglgrandlyon', async () => { + const mockQueryResult: QueryResult<Account[]> = { + data: [accountsData[2]], + bookmark: '', + next: false, + skip: 0, + } + mockClient.query.mockResolvedValueOnce(mockQueryResult) + const mockType = 'eglgrandlyon' + const result = await accountService.getAccountByType(mockType) + expect(result).toEqual(accountsData[2]) + }) + + it('should return null when no account find', async () => { + const mockQueryResult: QueryResult<Account[]> = { + data: [], + bookmark: '', + next: false, + skip: 0, + } + mockClient.query.mockResolvedValueOnce(mockQueryResult) + const mockType = 'eglgrandlyon' + const result = await accountService.getAccountByType(mockType) + expect(result).toBe(null) + }) + }) + + describe('updateAccount method', () => { + it('should return updated account when updateAccount successfully', async () => { + mockHavestLibAccounts.updateAccount.mockResolvedValueOnce(accountsData[2]) + const result = await accountService.updateAccount(accountsData[2]) + expect(result).toEqual(accountsData[2]) + }) + + it('should throw error when updateAccount unsuccessfully', async () => { + mockHavestLibAccounts.updateAccount.mockRejectedValueOnce(new Error()) + try { + await accountService.updateAccount(accountsData[2]) + } catch (error) { + expect(error).toEqual(new Error('Update account failed')) + } + }) + }) + + describe('deleteAccount method', () => { + it('should return true when destroy successfully', async () => { + mockHavestLibAccounts.deleteAccount.mockResolvedValueOnce(accountsData[2]) + const result = await accountService.deleteAccount(accountsData[2]) + expect(result).toBe(true) + }) + + it('should throw error when destroy unsuccessfully', async () => { + mockHavestLibAccounts.deleteAccount.mockRejectedValueOnce(new Error()) + try { + await accountService.deleteAccount(accountsData[2]) + } catch (error) { + expect(error).toEqual(new Error('Delete account failed')) + } + }) + }) + + describe('createIndexAccount method', () => { + it('should return empty array', async () => { + const mockQueryResult: QueryResult<Account[]> = { + data: [], + bookmark: '', + next: false, + skip: 0, + } + mockClient.query.mockResolvedValueOnce(mockQueryResult) + const result = await accountService.createIndexAccount() + expect(result).toEqual([]) + }) + }) +}) diff --git a/src/services/action.service.spec.ts b/src/services/action.service.spec.ts index 2f838645cbe043f51ba7361ef1924384abd6097d..fba30cc272263f4531c6f4bd9e80bf64a7c65b79 100644 --- a/src/services/action.service.spec.ts +++ b/src/services/action.service.spec.ts @@ -1,172 +1,172 @@ -import { UserActionState } from 'enum/userAction.enum' -import { DateTime } from 'luxon' -import { Ecogesture, UserAction } from 'models' -import { - AllEcogestureData, - defaultEcogestureData, - ecogestureDefault, -} from '../../test/__mocks__/actionData.mock' -import mockClient from '../../test/__mocks__/client' -import { userChallengeData } from '../../test/__mocks__/userChallengeData.mock' -import ActionService from './action.service' - -const mockgetAllUserChallengeEntities = jest.fn() -jest.mock('./challenge.service', () => { - return jest.fn(() => { - return { - getAllUserChallengeEntities: mockgetAllUserChallengeEntities, - } - }) -}) - -const mockgetAllEcogestures = jest.fn() -const mockgetEcogesturesByIds = jest.fn() -jest.mock('./ecogesture.service', () => { - return jest.fn(() => { - return { - getAllEcogestures: mockgetAllEcogestures, - getEcogesturesByIds: mockgetEcogesturesByIds, - } - }) -}) - -describe('Action Service', () => { - const actionService = new ActionService(mockClient) - - it('shoud return the default actions', async () => { - mockgetAllEcogestures.mockResolvedValueOnce(AllEcogestureData) - mockgetEcogesturesByIds.mockResolvedValueOnce(defaultEcogestureData) - - const result: Ecogesture[] = await actionService.getDefaultActions() - expect(result).toEqual(defaultEcogestureData) - }) - it('shoud return the Available Action List', async () => { - mockgetAllUserChallengeEntities.mockResolvedValueOnce(userChallengeData) - mockgetAllEcogestures.mockResolvedValueOnce(AllEcogestureData) - mockgetEcogesturesByIds.mockResolvedValueOnce([ - AllEcogestureData[2], - AllEcogestureData[3], - AllEcogestureData[4], - ]) - - const result: Ecogesture[] = await actionService.getAvailableActionList() - expect(result).toEqual([ - AllEcogestureData[2], - AllEcogestureData[3], - AllEcogestureData[4], - ]) - }) - it('shoud return winter ecogestures', () => { - jest - .spyOn(DateTime, 'local') - .mockReturnValueOnce( - DateTime.fromISO('2021-01-01T00:00:00.000Z', { zone: 'utc' }) - ) - const result: Ecogesture[] = actionService.filterBySeason(AllEcogestureData) - expect(result).toEqual([ - AllEcogestureData[0], - AllEcogestureData[2], - AllEcogestureData[5], - ]) - }) - it('shoud return no season ecogestures', () => { - jest - .spyOn(DateTime, 'local') - .mockReturnValueOnce( - DateTime.fromISO('2020-04-01T00:00:00.000Z', { zone: 'utc' }) - ) - const result: Ecogesture[] = actionService.filterBySeason(AllEcogestureData) - - expect(result).toEqual([AllEcogestureData[3], AllEcogestureData[4]]) - }) - it('shoud return summer ecogestures', () => { - jest - .spyOn(DateTime, 'local') - .mockReturnValueOnce( - DateTime.fromISO('2020-08-01T00:00:00.000Z', { zone: 'utc' }) - ) - const result: Ecogesture[] = actionService.filterBySeason(AllEcogestureData) - - expect(result).toEqual([ - AllEcogestureData[1], - AllEcogestureData[3], - AllEcogestureData[4], - ]) - }) - - it('shoud launch an action', () => { - jest - .spyOn(DateTime, 'local') - .mockReturnValue( - DateTime.fromISO('2020-10-01T00:00:00.000Z', { zone: 'utc' }) - ) - const result: UserAction = actionService.launchAction(ecogestureDefault) - const UserActionDefault: UserAction = { - ecogesture: ecogestureDefault, - startDate: DateTime.fromISO('2020-10-01T00:00:00.000Z', { - zone: 'utc', - }), - state: UserActionState.ONGOING, - } - expect(result).toEqual(UserActionDefault) - }) - it('complete list if < 3', async () => { - mockgetEcogesturesByIds.mockResolvedValueOnce([ - AllEcogestureData[2], - AllEcogestureData[3], - AllEcogestureData[4], - ]) - const result = await actionService.keepListComplete([ - AllEcogestureData[0], - AllEcogestureData[1], - ]) - - expect(result).toEqual([ - AllEcogestureData[0], - AllEcogestureData[1], - AllEcogestureData[2], - ]) - }) - describe('getCustomActions function', () => { - it('shoud return filtered and sorted ecogestures and not complete the list', async () => { - mockgetAllUserChallengeEntities.mockResolvedValueOnce(userChallengeData) - mockgetAllEcogestures.mockResolvedValueOnce(AllEcogestureData) - mockgetEcogesturesByIds.mockResolvedValueOnce([ - AllEcogestureData[0], - AllEcogestureData[1], - AllEcogestureData[2], - AllEcogestureData[3], - AllEcogestureData[4], - AllEcogestureData[5], - ]) - const result = await actionService.getCustomActions([0, 2]) - expect(result).toEqual([ - AllEcogestureData[0], - AllEcogestureData[5], - AllEcogestureData[2], - ]) - }) - it('shoud return filtered and sorted ecogestures and complete the list with default ecogesture', async () => { - mockgetAllUserChallengeEntities.mockResolvedValueOnce(userChallengeData) - mockgetAllEcogestures.mockResolvedValueOnce(AllEcogestureData) - mockgetEcogesturesByIds.mockResolvedValueOnce([ - AllEcogestureData[0], - AllEcogestureData[1], - AllEcogestureData[2], - AllEcogestureData[3], - ]) - mockgetEcogesturesByIds.mockClear() - mockgetEcogesturesByIds.mockResolvedValueOnce([ - defaultEcogestureData[0], - defaultEcogestureData[1], - defaultEcogestureData[2], - ]) - const result = await actionService.getCustomActions([0, 2]) - expect(result).toEqual([ - AllEcogestureData[0], - defaultEcogestureData[0], - AllEcogestureData[2], - ]) - }) - }) -}) +import { UserActionState } from 'enum/userAction.enum' +import { DateTime } from 'luxon' +import { Ecogesture, UserAction } from 'models' +import { + AllEcogestureData, + defaultEcogestureData, + ecogestureDefault, +} from '../../tests/__mocks__/actionData.mock' +import mockClient from '../../tests/__mocks__/client' +import { userChallengeData } from '../../tests/__mocks__/userChallengeData.mock' +import ActionService from './action.service' + +const mockgetAllUserChallengeEntities = jest.fn() +jest.mock('./challenge.service', () => { + return jest.fn(() => { + return { + getAllUserChallengeEntities: mockgetAllUserChallengeEntities, + } + }) +}) + +const mockgetAllEcogestures = jest.fn() +const mockgetEcogesturesByIds = jest.fn() +jest.mock('./ecogesture.service', () => { + return jest.fn(() => { + return { + getAllEcogestures: mockgetAllEcogestures, + getEcogesturesByIds: mockgetEcogesturesByIds, + } + }) +}) + +describe('Action Service', () => { + const actionService = new ActionService(mockClient) + + it('shoud return the default actions', async () => { + mockgetAllEcogestures.mockResolvedValueOnce(AllEcogestureData) + mockgetEcogesturesByIds.mockResolvedValueOnce(defaultEcogestureData) + + const result: Ecogesture[] = await actionService.getDefaultActions() + expect(result).toEqual(defaultEcogestureData) + }) + it('shoud return the Available Action List', async () => { + mockgetAllUserChallengeEntities.mockResolvedValueOnce(userChallengeData) + mockgetAllEcogestures.mockResolvedValueOnce(AllEcogestureData) + mockgetEcogesturesByIds.mockResolvedValueOnce([ + AllEcogestureData[2], + AllEcogestureData[3], + AllEcogestureData[4], + ]) + + const result: Ecogesture[] = await actionService.getAvailableActionList() + expect(result).toEqual([ + AllEcogestureData[2], + AllEcogestureData[3], + AllEcogestureData[4], + ]) + }) + it('shoud return winter ecogestures', () => { + jest + .spyOn(DateTime, 'local') + .mockReturnValueOnce( + DateTime.fromISO('2021-01-01T00:00:00.000Z', { zone: 'utc' }) + ) + const result: Ecogesture[] = actionService.filterBySeason(AllEcogestureData) + expect(result).toEqual([ + AllEcogestureData[0], + AllEcogestureData[2], + AllEcogestureData[5], + ]) + }) + it('shoud return no season ecogestures', () => { + jest + .spyOn(DateTime, 'local') + .mockReturnValueOnce( + DateTime.fromISO('2020-04-01T00:00:00.000Z', { zone: 'utc' }) + ) + const result: Ecogesture[] = actionService.filterBySeason(AllEcogestureData) + + expect(result).toEqual([AllEcogestureData[3], AllEcogestureData[4]]) + }) + it('shoud return summer ecogestures', () => { + jest + .spyOn(DateTime, 'local') + .mockReturnValueOnce( + DateTime.fromISO('2020-08-01T00:00:00.000Z', { zone: 'utc' }) + ) + const result: Ecogesture[] = actionService.filterBySeason(AllEcogestureData) + + expect(result).toEqual([ + AllEcogestureData[1], + AllEcogestureData[3], + AllEcogestureData[4], + ]) + }) + + it('shoud launch an action', () => { + jest + .spyOn(DateTime, 'local') + .mockReturnValue( + DateTime.fromISO('2020-10-01T00:00:00.000Z', { zone: 'utc' }) + ) + const result: UserAction = actionService.launchAction(ecogestureDefault) + const UserActionDefault: UserAction = { + ecogesture: ecogestureDefault, + startDate: DateTime.fromISO('2020-10-01T00:00:00.000Z', { + zone: 'utc', + }), + state: UserActionState.ONGOING, + } + expect(result).toEqual(UserActionDefault) + }) + it('complete list if < 3', async () => { + mockgetEcogesturesByIds.mockResolvedValueOnce([ + AllEcogestureData[2], + AllEcogestureData[3], + AllEcogestureData[4], + ]) + const result = await actionService.keepListComplete([ + AllEcogestureData[0], + AllEcogestureData[1], + ]) + + expect(result).toEqual([ + AllEcogestureData[0], + AllEcogestureData[1], + AllEcogestureData[2], + ]) + }) + describe('getCustomActions function', () => { + it('shoud return filtered and sorted ecogestures and not complete the list', async () => { + mockgetAllUserChallengeEntities.mockResolvedValueOnce(userChallengeData) + mockgetAllEcogestures.mockResolvedValueOnce(AllEcogestureData) + mockgetEcogesturesByIds.mockResolvedValueOnce([ + AllEcogestureData[0], + AllEcogestureData[1], + AllEcogestureData[2], + AllEcogestureData[3], + AllEcogestureData[4], + AllEcogestureData[5], + ]) + const result = await actionService.getCustomActions([0, 2]) + expect(result).toEqual([ + AllEcogestureData[0], + AllEcogestureData[5], + AllEcogestureData[2], + ]) + }) + it('shoud return filtered and sorted ecogestures and complete the list with default ecogesture', async () => { + mockgetAllUserChallengeEntities.mockResolvedValueOnce(userChallengeData) + mockgetAllEcogestures.mockResolvedValueOnce(AllEcogestureData) + mockgetEcogesturesByIds.mockResolvedValueOnce([ + AllEcogestureData[0], + AllEcogestureData[1], + AllEcogestureData[2], + AllEcogestureData[3], + ]) + mockgetEcogesturesByIds.mockClear() + mockgetEcogesturesByIds.mockResolvedValueOnce([ + defaultEcogestureData[0], + defaultEcogestureData[1], + defaultEcogestureData[2], + ]) + const result = await actionService.getCustomActions([0, 2]) + expect(result).toEqual([ + AllEcogestureData[0], + defaultEcogestureData[0], + AllEcogestureData[2], + ]) + }) + }) +}) diff --git a/src/services/challenge.service.spec.ts b/src/services/challenge.service.spec.ts index b2cf3b40d6639ed62b70b9ebae60c05498d548d3..70ab9dec1bfc8022d5595674755ad41e3f768aeb 100644 --- a/src/services/challenge.service.spec.ts +++ b/src/services/challenge.service.spec.ts @@ -20,21 +20,21 @@ import { userChallengeExplo1OnGoing, userChallengeExplo4, userChallengeExplo4_0, -} from '../../test/__mocks__/userChallengeData.mock' -import mockClient from '../../test/__mocks__/client' +} from '../../tests/__mocks__/userChallengeData.mock' +import mockClient from '../../tests/__mocks__/client' import { allChallengeEntityData, challengeEntityData, -} from '../../test/__mocks__/challengeEntity.mock' +} from '../../tests/__mocks__/challengeEntity.mock' import { allDuelEntity, duelData, duelEntity, -} from '../../test/__mocks__/duelData.mock' +} from '../../tests/__mocks__/duelData.mock' import { DateTime, Duration } from 'luxon' -import { graphData } from '../../test/__mocks__/datachartData.mock' +import { graphData } from '../../tests/__mocks__/datachartData.mock' import { UserDuelState } from 'enum/userDuel.enum' -import { quizEntity, userQuiz } from '../../test/__mocks__/quizData.mock' +import { quizEntity, userQuiz } from '../../tests/__mocks__/quizData.mock' import { explorationDefault, explorationEntity, @@ -45,8 +45,8 @@ import { userExploration4, userExploration4_0, UserExplorationUnlocked, -} from '../../test/__mocks__/explorationData.mock' -import { fluidStatusData } from '../../test/__mocks__/fluidStatusData.mock' +} from '../../tests/__mocks__/explorationData.mock' +import { fluidStatusData } from '../../tests/__mocks__/fluidStatusData.mock' import { cloneDeep } from 'lodash' import { UserActionState } from 'enum/userAction.enum' diff --git a/src/services/connection.service.spec.ts b/src/services/connection.service.spec.ts index 657c4d15fa1a97563b6d84826735b1660490e424..c2a73b9eb3460706591f67b62da3a683c8bb0012 100644 --- a/src/services/connection.service.spec.ts +++ b/src/services/connection.service.spec.ts @@ -1,98 +1,98 @@ -import ConnectionService from './connection.service' -import mockClient from '../../test/__mocks__/client' -import { konnectorsData } from '../../test/__mocks__/konnectorsData.mock' -import { accountsData } from '../../test/__mocks__/accountsData.mock' -import { triggersData } from '../../test/__mocks__/triggersData.mock' - -const mockGetKonnector = jest.fn() -jest.mock('./konnector.service', () => { - return jest.fn(() => { - return { - getKonnector: mockGetKonnector, - } - }) -}) - -const mockCreateAccount = jest.fn() -jest.mock('./account.service', () => { - return jest.fn(() => { - return { - createAccount: mockCreateAccount, - } - }) -}) - -const mockCreateTrigger = jest.fn() -jest.mock('./triggers.service', () => { - return jest.fn(() => { - return { - createTrigger: mockCreateTrigger, - } - }) -}) - -describe('Connection service', () => { - const connectionService = new ConnectionService(mockClient) - - describe('connectNewUser method', () => { - it('shoud return created Trigger', async () => { - mockGetKonnector.mockResolvedValueOnce(konnectorsData[0]) - mockCreateAccount.mockResolvedValueOnce(accountsData[0]) - mockCreateTrigger.mockResolvedValueOnce(triggersData[0]) - const mockResult = { account: accountsData[0], trigger: triggersData[0] } - const result = await connectionService.connectNewUser( - konnectorsData[0]._id, - 'login', - 'password' - ) - expect(result).toEqual(mockResult) - }) - - it('shoud throw error when konnector is not found', async () => { - let error - try { - await connectionService.connectNewUser( - konnectorsData[0]._id, - 'login', - 'password' - ) - } catch (err) { - error = err - } - expect(error).toEqual( - new Error(`Could not find konnector for ${konnectorsData[0]._id}`) - ) - }) - - it('shoud throw error when account is not created', async () => { - mockGetKonnector.mockResolvedValueOnce(konnectorsData[0]) - let error - try { - await connectionService.connectNewUser( - konnectorsData[0]._id, - 'login', - 'password' - ) - } catch (err) { - error = err - } - expect(error).toEqual(new Error(`Error during account creation`)) - }) - - it('shoud throw error when trigger is not created', async () => { - mockGetKonnector.mockResolvedValueOnce(konnectorsData[0]) - mockCreateAccount.mockResolvedValueOnce(accountsData[0]) - let error - try { - await connectionService.connectNewUser( - konnectorsData[0]._id, - 'login', - 'password' - ) - } catch (err) { - error = err - } - expect(error).toEqual(new Error(`Error during trigger creation`)) - }) - }) -}) +import ConnectionService from './connection.service' +import mockClient from '../../tests/__mocks__/client' +import { konnectorsData } from '../../tests/__mocks__/konnectorsData.mock' +import { accountsData } from '../../tests/__mocks__/accountsData.mock' +import { triggersData } from '../../tests/__mocks__/triggersData.mock' + +const mockGetKonnector = jest.fn() +jest.mock('./konnector.service', () => { + return jest.fn(() => { + return { + getKonnector: mockGetKonnector, + } + }) +}) + +const mockCreateAccount = jest.fn() +jest.mock('./account.service', () => { + return jest.fn(() => { + return { + createAccount: mockCreateAccount, + } + }) +}) + +const mockCreateTrigger = jest.fn() +jest.mock('./triggers.service', () => { + return jest.fn(() => { + return { + createTrigger: mockCreateTrigger, + } + }) +}) + +describe('Connection service', () => { + const connectionService = new ConnectionService(mockClient) + + describe('connectNewUser method', () => { + it('shoud return created Trigger', async () => { + mockGetKonnector.mockResolvedValueOnce(konnectorsData[0]) + mockCreateAccount.mockResolvedValueOnce(accountsData[0]) + mockCreateTrigger.mockResolvedValueOnce(triggersData[0]) + const mockResult = { account: accountsData[0], trigger: triggersData[0] } + const result = await connectionService.connectNewUser( + konnectorsData[0]._id, + 'login', + 'password' + ) + expect(result).toEqual(mockResult) + }) + + it('shoud throw error when konnector is not found', async () => { + let error + try { + await connectionService.connectNewUser( + konnectorsData[0]._id, + 'login', + 'password' + ) + } catch (err) { + error = err + } + expect(error).toEqual( + new Error(`Could not find konnector for ${konnectorsData[0]._id}`) + ) + }) + + it('shoud throw error when account is not created', async () => { + mockGetKonnector.mockResolvedValueOnce(konnectorsData[0]) + let error + try { + await connectionService.connectNewUser( + konnectorsData[0]._id, + 'login', + 'password' + ) + } catch (err) { + error = err + } + expect(error).toEqual(new Error(`Error during account creation`)) + }) + + it('shoud throw error when trigger is not created', async () => { + mockGetKonnector.mockResolvedValueOnce(konnectorsData[0]) + mockCreateAccount.mockResolvedValueOnce(accountsData[0]) + let error + try { + await connectionService.connectNewUser( + konnectorsData[0]._id, + 'login', + 'password' + ) + } catch (err) { + error = err + } + expect(error).toEqual(new Error(`Error during trigger creation`)) + }) + }) +}) diff --git a/src/services/consumption.service.spec.ts b/src/services/consumption.service.spec.ts index 60d42def294134f06c828ba5a08b346f883a2e04..ed1c14666e930f3cfba592870cb988f8675ad93f 100644 --- a/src/services/consumption.service.spec.ts +++ b/src/services/consumption.service.spec.ts @@ -1,418 +1,418 @@ -import ConsumptionDataManager from './consumption.service' -import mockClient from '../../test/__mocks__/client' -import { TimeStep } from 'enum/timeStep.enum' -import { DateTime } from 'luxon' -import { FluidType } from 'enum/fluid.enum' -import { Dataload, TimePeriod } from 'models' - -const mockFetchFluidData = jest.fn() -const mockFetchFluidMaxData = jest.fn() -const mockGetLastDateData = jest.fn() -const mockGetEntries = jest.fn() -jest.mock('./queryRunner.service', () => { - return jest.fn(() => { - return { - fetchFluidData: mockFetchFluidData, - fetchFluidMaxData: mockFetchFluidMaxData, - getLastDateData: mockGetLastDateData, - getEntries: mockGetEntries, - } - }) -}) - -describe('Consumption service', () => { - const consumptionDataManager = new ConsumptionDataManager(mockClient) - let fluidTypes: FluidType[] = [0] - const mockTimePeriod: TimePeriod = { - startDate: DateTime.fromISO('2020-10-01T00:00:00.000Z'), - endDate: DateTime.fromISO('2020-10-03T23:59:59.999Z'), - } - const mockTimePeriodComparison: TimePeriod = { - startDate: DateTime.fromISO('2020-09-01T00:00:00.000Z'), - endDate: DateTime.fromISO('2020-09-03T23:59:59.999Z'), - } - const mockFetchDataActual: Dataload[] = [ - { - date: DateTime.fromISO('2020-10-01T00:00:00.000Z'), - value: 291.9, - valueDetail: null, - }, - { - date: DateTime.fromISO('2020-10-02T00:00:00.000Z'), - value: 260.15, - valueDetail: null, - }, - ] - const mockFetchDataComparison: Dataload[] = [ - { - date: DateTime.fromISO('2020-09-01T00:00:00.000Z'), - value: 228.23, - valueDetail: null, - }, - { - date: DateTime.fromISO('2020-09-02T00:00:00.000Z'), - value: 238.71, - valueDetail: null, - }, - ] - describe('getGraphData method', () => { - it('should return null', async () => { - const result = await consumptionDataManager.getGraphData( - mockTimePeriod, - TimeStep.DAY, - [], - mockTimePeriodComparison, - false - ) - expect(result).toBeNull() - }) - it('shoud return a mapped data for one fluid', async () => { - mockFetchFluidData.mockResolvedValueOnce(mockFetchDataActual) - mockFetchFluidData.mockResolvedValueOnce(mockFetchDataComparison) - const mockResult = { - actualData: [ - { - date: DateTime.fromISO('2020-10-01T00:00:00.000Z'), - value: 291.9, - valueDetail: null, - }, - { - date: DateTime.fromISO('2020-10-02T00:00:00.000Z'), - value: 260.15, - valueDetail: null, - }, - { - date: DateTime.fromISO('2020-10-03T00:00:00.000Z'), - value: -1, - valueDetail: null, - }, - ], - comparisonData: [ - { - date: DateTime.fromISO('2020-09-01T00:00:00.000Z'), - value: 228.23, - valueDetail: null, - }, - { - date: DateTime.fromISO('2020-09-02T00:00:00.000Z'), - value: 238.71, - valueDetail: null, - }, - { - date: DateTime.fromISO('2020-09-03T00:00:00.000Z'), - value: -1, - valueDetail: null, - }, - ], - } - const result = await consumptionDataManager.getGraphData( - mockTimePeriod, - TimeStep.DAY, - fluidTypes, - mockTimePeriodComparison, - false - ) - expect(result).toEqual(mockResult) - }) - - it('should return a mapped data for multiple fluid', async () => { - fluidTypes = [0, 1, 2] - for (let i = 0; i < fluidTypes.length; i++) { - mockFetchFluidData.mockResolvedValueOnce(mockFetchDataActual) - mockFetchFluidData.mockResolvedValueOnce(mockFetchDataComparison) - } - - const mockResult = { - actualData: [ - { - date: DateTime.fromISO('2020-10-01T00:00:00.000Z'), - value: 69.18029999999999, - valueDetail: [ - 45.127739999999996, - 0.9048899999999999, - 23.147669999999998, - ], - }, - { - date: DateTime.fromISO('2020-10-02T00:00:00.000Z'), - value: 61.65554999999999, - valueDetail: [ - 40.21918999999999, - 0.8064649999999999, - 20.629894999999998, - ], - }, - { - date: DateTime.fromISO('2020-10-03T00:00:00.000Z'), - value: -1, - valueDetail: null, - }, - ], - comparisonData: [ - { - date: DateTime.fromISO('2020-09-01T00:00:00.000Z'), - value: 54.090509999999995, - valueDetail: [35.284358, 0.707513, 18.098639], - }, - { - date: DateTime.fromISO('2020-09-02T00:00:00.000Z'), - value: 56.57427, - valueDetail: [36.904565999999996, 0.740001, 18.929703], - }, - { - date: DateTime.fromISO('2020-09-03T00:00:00.000Z'), - value: -1, - valueDetail: null, - }, - ], - } - const result = await consumptionDataManager.getGraphData( - mockTimePeriod, - TimeStep.DAY, - fluidTypes, - mockTimePeriodComparison, - true - ) - expect(result).toEqual(mockResult) - }) - it('should return a mapped data for one fluid without comparison date', async () => { - const mockResult = { - actualData: [ - { - date: DateTime.fromISO('2020-10-01T00:00:00.000Z'), - value: 69.18029999999999, - valueDetail: [ - 45.127739999999996, - 0.9048899999999999, - 23.147669999999998, - ], - }, - { - date: DateTime.fromISO('2020-10-02T00:00:00.000Z'), - value: 61.65554999999999, - valueDetail: [ - 40.21918999999999, - 0.8064649999999999, - 20.629894999999998, - ], - }, - { - date: DateTime.fromISO('2020-10-03T00:00:00.000Z'), - value: -1, - valueDetail: null, - }, - ], - comparisonData: [], - } - for (let i = 0; i < fluidTypes.length; i++) { - mockFetchFluidData.mockResolvedValueOnce(mockFetchDataActual) - } - const result = await consumptionDataManager.getGraphData( - mockTimePeriod, - TimeStep.DAY, - fluidTypes - ) - expect(result).toEqual(mockResult) - }) - it('should return null because of wrong parameters', async () => { - const mockFluidTypes = [1] - const result = await consumptionDataManager.getGraphData( - mockTimePeriod, - TimeStep.DAY, - mockFluidTypes, - mockTimePeriodComparison, - true - ) - expect(result).toBeNull() - }) - it('should return null because of timePeriod and comparaison', async () => { - const wrongTimePeriod = { - startDate: DateTime.fromISO('2020-10-03T23:59:59.999Z'), - endDate: DateTime.fromISO('2020-10-01T00:00:00.000Z'), - } - const result = await consumptionDataManager.getGraphData( - wrongTimePeriod, - TimeStep.DAY, - fluidTypes, - mockTimePeriodComparison, - true - ) - expect(result).toBeNull() - }) - }) - describe('getMaxLoad method', () => { - it('shoud return the maxed value for a time period for the home', async () => { - for (let i = 0; i < fluidTypes.length; i++) { - mockFetchFluidData.mockResolvedValueOnce(mockFetchDataActual) - mockFetchFluidData.mockResolvedValueOnce(mockFetchDataComparison) - } - const expectedResult = 69.18029999999999 - const result = await consumptionDataManager.getMaxLoad( - mockTimePeriod, - TimeStep.DAY, - fluidTypes, - mockTimePeriodComparison, - true - ) - expect(result).toEqual(expectedResult) - }) - it('shoud return the maxed value for a time period', async () => { - const mockFluidTypes = [1] - const expectedResult = 63.1254 - mockFetchFluidMaxData.mockResolvedValueOnce(expectedResult) - const result = await consumptionDataManager.getMaxLoad( - mockTimePeriod, - TimeStep.DAY, - mockFluidTypes, - mockTimePeriodComparison, - false - ) - expect(result).toEqual(expectedResult) - }) - }) - describe('getPerformanceIndicators method', () => { - it('shoud return the performance indicator', async () => { - mockFetchFluidData.mockResolvedValueOnce(mockFetchDataActual) - mockFetchFluidData.mockResolvedValueOnce(mockFetchDataComparison) - mockFetchFluidData.mockResolvedValueOnce(mockFetchDataActual) - mockFetchFluidData.mockResolvedValueOnce(mockFetchDataComparison) - //Incomplete Data to test all possibilities - mockFetchFluidData.mockResolvedValueOnce([ - { - date: DateTime.fromISO('2020-10-01T00:23:20.000Z'), - value: 298.283, - }, - ]) - mockFetchFluidData.mockResolvedValueOnce([ - { - date: DateTime.fromISO('2020-10-01T03:10:00.000Z'), - value: 398.283, - }, - ]) - - const mockTimePeriodComplete = { - startDate: DateTime.fromISO('2020-10-01T00:00:00.000Z'), - endDate: DateTime.fromISO('2020-10-02T23:59:59.999Z'), - } - const mockTimePeriodComparisonComplete = { - startDate: DateTime.fromISO('2020-09-01T00:00:00.000Z'), - endDate: DateTime.fromISO('2020-09-02T23:59:59.999Z'), - } - const expectedResult = [ - { - compareValue: 466.94, - percentageVariation: -0.18227181222426858, - value: 552.05, - }, - { - compareValue: 466.94, - percentageVariation: -0.18227181222426858, - value: 552.05, - }, - { compareValue: null, percentageVariation: null, value: null }, - ] - const result = await consumptionDataManager.getPerformanceIndicators( - mockTimePeriodComplete, - TimeStep.DAY, - fluidTypes, - mockTimePeriodComparisonComplete - ) - expect(result).toEqual(expectedResult) - }) - }) - describe('fetchLastDateData method', () => { - it('shoud return the latest date data of one fluid', async () => { - const mockFluidTypes = [0] - const expectedResult = DateTime.fromISO('2020-09-03T23:59:59.999Z') - mockGetLastDateData.mockResolvedValueOnce( - DateTime.fromISO('2020-09-03T23:59:59.999Z') - ) - const result = await consumptionDataManager.fetchLastDateData( - mockFluidTypes - ) - expect(result).toEqual(expectedResult) - }) - it('shoud return the latest date data of multiple fluid', async () => { - const mockFluidTypes = [0, 2] - mockGetLastDateData.mockResolvedValueOnce( - DateTime.fromISO('2020-09-03T23:59:59.999Z') - ) - mockGetLastDateData.mockResolvedValueOnce( - DateTime.fromISO('2020-09-02T23:59:59.999Z') - ) - const expectedResult = DateTime.fromISO('2020-09-03T23:59:59.999Z') - const result = await consumptionDataManager.fetchLastDateData( - mockFluidTypes - ) - expect(result).toEqual(expectedResult) - }) - it('shoud return the latest date data of all fluids', async () => { - mockGetLastDateData.mockResolvedValueOnce( - DateTime.fromISO('2020-09-02T23:59:59.999Z') - ) - mockGetLastDateData.mockResolvedValueOnce( - DateTime.fromISO('2020-09-03T23:59:59.999Z') - ) - mockGetLastDateData.mockResolvedValueOnce( - DateTime.fromISO('2020-09-01T23:59:59.999Z') - ) - const expectedResult = DateTime.fromISO('2020-09-01T23:59:59.999Z') - const result = await consumptionDataManager.fetchLastDateData( - fluidTypes, - true - ) - expect(result).toEqual(expectedResult) - }) - }) - describe('fetchAllLastDateData method', () => { - it('shoud return the latest date data of one fluid', async () => { - const mockFluidTypes = [0] - const expectedResult = [DateTime.fromISO('2020-09-03T23:59:59.999Z')] - mockGetLastDateData.mockResolvedValueOnce( - DateTime.fromISO('2020-09-03T23:59:59.999Z') - ) - const result = await consumptionDataManager.fetchAllLastDateData( - mockFluidTypes - ) - expect(result).toEqual(expectedResult) - }) - it('shoud return the latest date data of All fluid', async () => { - mockGetLastDateData.mockResolvedValueOnce( - DateTime.fromISO('2020-09-02T23:59:59.999Z') - ) - mockGetLastDateData.mockResolvedValueOnce( - DateTime.fromISO('2020-09-03T23:59:59.999Z') - ) - mockGetLastDateData.mockResolvedValueOnce( - DateTime.fromISO('2020-09-01T23:59:59.999Z') - ) - const expectedResult = [ - DateTime.fromISO('2020-09-02T23:59:59.999Z'), - DateTime.fromISO('2020-09-03T23:59:59.999Z'), - DateTime.fromISO('2020-09-01T23:59:59.999Z'), - ] - const result = await consumptionDataManager.fetchAllLastDateData( - fluidTypes - ) - expect(result).toEqual(expectedResult) - }) - }) - describe('checkDoctypeEntries method', () => { - it('shoud return a boolean if doctype are correct', async () => { - let fluidType = 2 - mockGetEntries.mockResolvedValueOnce({ data: [1] }) - let result = await consumptionDataManager.checkDoctypeEntries( - fluidType, - TimeStep.DAY - ) - expect(result).toBeTruthy() - fluidType = 999 - mockGetEntries.mockResolvedValueOnce({ data: [] }) - result = await consumptionDataManager.checkDoctypeEntries( - fluidType, - TimeStep.DAY - ) - expect(result).toBeFalsy() - }) - }) -}) +import ConsumptionDataManager from './consumption.service' +import mockClient from '../../tests/__mocks__/client' +import { TimeStep } from 'enum/timeStep.enum' +import { DateTime } from 'luxon' +import { FluidType } from 'enum/fluid.enum' +import { Dataload, TimePeriod } from 'models' + +const mockFetchFluidData = jest.fn() +const mockFetchFluidMaxData = jest.fn() +const mockGetLastDateData = jest.fn() +const mockGetEntries = jest.fn() +jest.mock('./queryRunner.service', () => { + return jest.fn(() => { + return { + fetchFluidData: mockFetchFluidData, + fetchFluidMaxData: mockFetchFluidMaxData, + getLastDateData: mockGetLastDateData, + getEntries: mockGetEntries, + } + }) +}) + +describe('Consumption service', () => { + const consumptionDataManager = new ConsumptionDataManager(mockClient) + let fluidTypes: FluidType[] = [0] + const mockTimePeriod: TimePeriod = { + startDate: DateTime.fromISO('2020-10-01T00:00:00.000Z'), + endDate: DateTime.fromISO('2020-10-03T23:59:59.999Z'), + } + const mockTimePeriodComparison: TimePeriod = { + startDate: DateTime.fromISO('2020-09-01T00:00:00.000Z'), + endDate: DateTime.fromISO('2020-09-03T23:59:59.999Z'), + } + const mockFetchDataActual: Dataload[] = [ + { + date: DateTime.fromISO('2020-10-01T00:00:00.000Z'), + value: 291.9, + valueDetail: null, + }, + { + date: DateTime.fromISO('2020-10-02T00:00:00.000Z'), + value: 260.15, + valueDetail: null, + }, + ] + const mockFetchDataComparison: Dataload[] = [ + { + date: DateTime.fromISO('2020-09-01T00:00:00.000Z'), + value: 228.23, + valueDetail: null, + }, + { + date: DateTime.fromISO('2020-09-02T00:00:00.000Z'), + value: 238.71, + valueDetail: null, + }, + ] + describe('getGraphData method', () => { + it('should return null', async () => { + const result = await consumptionDataManager.getGraphData( + mockTimePeriod, + TimeStep.DAY, + [], + mockTimePeriodComparison, + false + ) + expect(result).toBeNull() + }) + it('shoud return a mapped data for one fluid', async () => { + mockFetchFluidData.mockResolvedValueOnce(mockFetchDataActual) + mockFetchFluidData.mockResolvedValueOnce(mockFetchDataComparison) + const mockResult = { + actualData: [ + { + date: DateTime.fromISO('2020-10-01T00:00:00.000Z'), + value: 291.9, + valueDetail: null, + }, + { + date: DateTime.fromISO('2020-10-02T00:00:00.000Z'), + value: 260.15, + valueDetail: null, + }, + { + date: DateTime.fromISO('2020-10-03T00:00:00.000Z'), + value: -1, + valueDetail: null, + }, + ], + comparisonData: [ + { + date: DateTime.fromISO('2020-09-01T00:00:00.000Z'), + value: 228.23, + valueDetail: null, + }, + { + date: DateTime.fromISO('2020-09-02T00:00:00.000Z'), + value: 238.71, + valueDetail: null, + }, + { + date: DateTime.fromISO('2020-09-03T00:00:00.000Z'), + value: -1, + valueDetail: null, + }, + ], + } + const result = await consumptionDataManager.getGraphData( + mockTimePeriod, + TimeStep.DAY, + fluidTypes, + mockTimePeriodComparison, + false + ) + expect(result).toEqual(mockResult) + }) + + it('should return a mapped data for multiple fluid', async () => { + fluidTypes = [0, 1, 2] + for (let i = 0; i < fluidTypes.length; i++) { + mockFetchFluidData.mockResolvedValueOnce(mockFetchDataActual) + mockFetchFluidData.mockResolvedValueOnce(mockFetchDataComparison) + } + + const mockResult = { + actualData: [ + { + date: DateTime.fromISO('2020-10-01T00:00:00.000Z'), + value: 69.18029999999999, + valueDetail: [ + 45.127739999999996, + 0.9048899999999999, + 23.147669999999998, + ], + }, + { + date: DateTime.fromISO('2020-10-02T00:00:00.000Z'), + value: 61.65554999999999, + valueDetail: [ + 40.21918999999999, + 0.8064649999999999, + 20.629894999999998, + ], + }, + { + date: DateTime.fromISO('2020-10-03T00:00:00.000Z'), + value: -1, + valueDetail: null, + }, + ], + comparisonData: [ + { + date: DateTime.fromISO('2020-09-01T00:00:00.000Z'), + value: 54.090509999999995, + valueDetail: [35.284358, 0.707513, 18.098639], + }, + { + date: DateTime.fromISO('2020-09-02T00:00:00.000Z'), + value: 56.57427, + valueDetail: [36.904565999999996, 0.740001, 18.929703], + }, + { + date: DateTime.fromISO('2020-09-03T00:00:00.000Z'), + value: -1, + valueDetail: null, + }, + ], + } + const result = await consumptionDataManager.getGraphData( + mockTimePeriod, + TimeStep.DAY, + fluidTypes, + mockTimePeriodComparison, + true + ) + expect(result).toEqual(mockResult) + }) + it('should return a mapped data for one fluid without comparison date', async () => { + const mockResult = { + actualData: [ + { + date: DateTime.fromISO('2020-10-01T00:00:00.000Z'), + value: 69.18029999999999, + valueDetail: [ + 45.127739999999996, + 0.9048899999999999, + 23.147669999999998, + ], + }, + { + date: DateTime.fromISO('2020-10-02T00:00:00.000Z'), + value: 61.65554999999999, + valueDetail: [ + 40.21918999999999, + 0.8064649999999999, + 20.629894999999998, + ], + }, + { + date: DateTime.fromISO('2020-10-03T00:00:00.000Z'), + value: -1, + valueDetail: null, + }, + ], + comparisonData: [], + } + for (let i = 0; i < fluidTypes.length; i++) { + mockFetchFluidData.mockResolvedValueOnce(mockFetchDataActual) + } + const result = await consumptionDataManager.getGraphData( + mockTimePeriod, + TimeStep.DAY, + fluidTypes + ) + expect(result).toEqual(mockResult) + }) + it('should return null because of wrong parameters', async () => { + const mockFluidTypes = [1] + const result = await consumptionDataManager.getGraphData( + mockTimePeriod, + TimeStep.DAY, + mockFluidTypes, + mockTimePeriodComparison, + true + ) + expect(result).toBeNull() + }) + it('should return null because of timePeriod and comparaison', async () => { + const wrongTimePeriod = { + startDate: DateTime.fromISO('2020-10-03T23:59:59.999Z'), + endDate: DateTime.fromISO('2020-10-01T00:00:00.000Z'), + } + const result = await consumptionDataManager.getGraphData( + wrongTimePeriod, + TimeStep.DAY, + fluidTypes, + mockTimePeriodComparison, + true + ) + expect(result).toBeNull() + }) + }) + describe('getMaxLoad method', () => { + it('shoud return the maxed value for a time period for the home', async () => { + for (let i = 0; i < fluidTypes.length; i++) { + mockFetchFluidData.mockResolvedValueOnce(mockFetchDataActual) + mockFetchFluidData.mockResolvedValueOnce(mockFetchDataComparison) + } + const expectedResult = 69.18029999999999 + const result = await consumptionDataManager.getMaxLoad( + mockTimePeriod, + TimeStep.DAY, + fluidTypes, + mockTimePeriodComparison, + true + ) + expect(result).toEqual(expectedResult) + }) + it('shoud return the maxed value for a time period', async () => { + const mockFluidTypes = [1] + const expectedResult = 63.1254 + mockFetchFluidMaxData.mockResolvedValueOnce(expectedResult) + const result = await consumptionDataManager.getMaxLoad( + mockTimePeriod, + TimeStep.DAY, + mockFluidTypes, + mockTimePeriodComparison, + false + ) + expect(result).toEqual(expectedResult) + }) + }) + describe('getPerformanceIndicators method', () => { + it('shoud return the performance indicator', async () => { + mockFetchFluidData.mockResolvedValueOnce(mockFetchDataActual) + mockFetchFluidData.mockResolvedValueOnce(mockFetchDataComparison) + mockFetchFluidData.mockResolvedValueOnce(mockFetchDataActual) + mockFetchFluidData.mockResolvedValueOnce(mockFetchDataComparison) + //Incomplete Data to test all possibilities + mockFetchFluidData.mockResolvedValueOnce([ + { + date: DateTime.fromISO('2020-10-01T00:23:20.000Z'), + value: 298.283, + }, + ]) + mockFetchFluidData.mockResolvedValueOnce([ + { + date: DateTime.fromISO('2020-10-01T03:10:00.000Z'), + value: 398.283, + }, + ]) + + const mockTimePeriodComplete = { + startDate: DateTime.fromISO('2020-10-01T00:00:00.000Z'), + endDate: DateTime.fromISO('2020-10-02T23:59:59.999Z'), + } + const mockTimePeriodComparisonComplete = { + startDate: DateTime.fromISO('2020-09-01T00:00:00.000Z'), + endDate: DateTime.fromISO('2020-09-02T23:59:59.999Z'), + } + const expectedResult = [ + { + compareValue: 466.94, + percentageVariation: -0.18227181222426858, + value: 552.05, + }, + { + compareValue: 466.94, + percentageVariation: -0.18227181222426858, + value: 552.05, + }, + { compareValue: null, percentageVariation: null, value: null }, + ] + const result = await consumptionDataManager.getPerformanceIndicators( + mockTimePeriodComplete, + TimeStep.DAY, + fluidTypes, + mockTimePeriodComparisonComplete + ) + expect(result).toEqual(expectedResult) + }) + }) + describe('fetchLastDateData method', () => { + it('shoud return the latest date data of one fluid', async () => { + const mockFluidTypes = [0] + const expectedResult = DateTime.fromISO('2020-09-03T23:59:59.999Z') + mockGetLastDateData.mockResolvedValueOnce( + DateTime.fromISO('2020-09-03T23:59:59.999Z') + ) + const result = await consumptionDataManager.fetchLastDateData( + mockFluidTypes + ) + expect(result).toEqual(expectedResult) + }) + it('shoud return the latest date data of multiple fluid', async () => { + const mockFluidTypes = [0, 2] + mockGetLastDateData.mockResolvedValueOnce( + DateTime.fromISO('2020-09-03T23:59:59.999Z') + ) + mockGetLastDateData.mockResolvedValueOnce( + DateTime.fromISO('2020-09-02T23:59:59.999Z') + ) + const expectedResult = DateTime.fromISO('2020-09-03T23:59:59.999Z') + const result = await consumptionDataManager.fetchLastDateData( + mockFluidTypes + ) + expect(result).toEqual(expectedResult) + }) + it('shoud return the latest date data of all fluids', async () => { + mockGetLastDateData.mockResolvedValueOnce( + DateTime.fromISO('2020-09-02T23:59:59.999Z') + ) + mockGetLastDateData.mockResolvedValueOnce( + DateTime.fromISO('2020-09-03T23:59:59.999Z') + ) + mockGetLastDateData.mockResolvedValueOnce( + DateTime.fromISO('2020-09-01T23:59:59.999Z') + ) + const expectedResult = DateTime.fromISO('2020-09-01T23:59:59.999Z') + const result = await consumptionDataManager.fetchLastDateData( + fluidTypes, + true + ) + expect(result).toEqual(expectedResult) + }) + }) + describe('fetchAllLastDateData method', () => { + it('shoud return the latest date data of one fluid', async () => { + const mockFluidTypes = [0] + const expectedResult = [DateTime.fromISO('2020-09-03T23:59:59.999Z')] + mockGetLastDateData.mockResolvedValueOnce( + DateTime.fromISO('2020-09-03T23:59:59.999Z') + ) + const result = await consumptionDataManager.fetchAllLastDateData( + mockFluidTypes + ) + expect(result).toEqual(expectedResult) + }) + it('shoud return the latest date data of All fluid', async () => { + mockGetLastDateData.mockResolvedValueOnce( + DateTime.fromISO('2020-09-02T23:59:59.999Z') + ) + mockGetLastDateData.mockResolvedValueOnce( + DateTime.fromISO('2020-09-03T23:59:59.999Z') + ) + mockGetLastDateData.mockResolvedValueOnce( + DateTime.fromISO('2020-09-01T23:59:59.999Z') + ) + const expectedResult = [ + DateTime.fromISO('2020-09-02T23:59:59.999Z'), + DateTime.fromISO('2020-09-03T23:59:59.999Z'), + DateTime.fromISO('2020-09-01T23:59:59.999Z'), + ] + const result = await consumptionDataManager.fetchAllLastDateData( + fluidTypes + ) + expect(result).toEqual(expectedResult) + }) + }) + describe('checkDoctypeEntries method', () => { + it('shoud return a boolean if doctype are correct', async () => { + let fluidType = 2 + mockGetEntries.mockResolvedValueOnce({ data: [1] }) + let result = await consumptionDataManager.checkDoctypeEntries( + fluidType, + TimeStep.DAY + ) + expect(result).toBeTruthy() + fluidType = 999 + mockGetEntries.mockResolvedValueOnce({ data: [] }) + result = await consumptionDataManager.checkDoctypeEntries( + fluidType, + TimeStep.DAY + ) + expect(result).toBeFalsy() + }) + }) +}) diff --git a/src/services/duel.service.spec.ts b/src/services/duel.service.spec.ts index c3ec5a642ce960562f172cc9f407166baf0d9cc2..09a59b3ad6f2c4400c8e5d3b941cb48303bdd597 100644 --- a/src/services/duel.service.spec.ts +++ b/src/services/duel.service.spec.ts @@ -7,17 +7,17 @@ import { duelData, allDuelData, duelEntity, -} from '../../test/__mocks__/duelData.mock' -import mockClient from '../../test/__mocks__/client' +} from '../../tests/__mocks__/duelData.mock' +import mockClient from '../../tests/__mocks__/client' import { fluidStatusConnectedData, fluidStatusData, -} from '../../test/__mocks__/fluidStatusData.mock' +} from '../../tests/__mocks__/fluidStatusData.mock' import DuelService from 'services/duel.service' import { fullGraphData, graphData, -} from '../../test/__mocks__/datachartData.mock' +} from '../../tests/__mocks__/datachartData.mock' const mockGetPerformanceIndicators = jest.fn() const mockGetGraphData = jest.fn() diff --git a/src/services/ecogesture.service.spec.ts b/src/services/ecogesture.service.spec.ts index 8767626090c240fab29530c2709953302b794e1a..5bf8a16774253fa6c9a77d6cde929287460f42ae 100644 --- a/src/services/ecogesture.service.spec.ts +++ b/src/services/ecogesture.service.spec.ts @@ -1,252 +1,252 @@ -import { QueryResult } from 'cozy-client' -import { Ecogesture } from 'models' -import EcogestureService from './ecogesture.service' -import mockClient from '../../test/__mocks__/client' -import { - ecogesturesAirConditioningData, - ecogesturesColdWaterData, - ecogesturesCookingData, - ecogesturesData, - ecogesturesECSData, - ecogesturesElecSpecificData, - ecogesturesHeatingData, -} from '../../test/__mocks__/ecogesturesData.mock' -import { ProfileType } from 'models/profileType.model' -import { profileData } from '../../test/__mocks__/profile.mock' -import { IndividualOrCollective } from 'enum/profileType.enum' -import { FluidType } from 'enum/fluid.enum' - -describe('Ecogesture service', () => { - const ecogestureService = new EcogestureService(mockClient) - - describe('getAllEcogestures', () => { - it('shoud return all ecogestures', async () => { - const mockQueryResult: QueryResult<Ecogesture[]> = { - data: ecogesturesData, - bookmark: '', - next: false, - skip: 0, - } - mockClient.query.mockResolvedValueOnce(mockQueryResult) - const result = await ecogestureService.getAllEcogestures() - expect(result).toEqual(ecogesturesData) - }) - it('shoud return empty array when no ecogestures stored', async () => { - const mockQueryResult: QueryResult<Ecogesture[]> = { - data: [], - bookmark: '', - next: false, - skip: 0, - } - mockClient.query.mockResolvedValueOnce(mockQueryResult) - const result = await ecogestureService.getAllEcogestures() - expect(result).toEqual([]) - }) - }) - - describe('deleteAllEcogestures', () => { - it('shoud return true when 3 ecogestures stored', async () => { - const mockQueryResult: QueryResult<Ecogesture[]> = { - data: ecogesturesData, - bookmark: '', - next: false, - skip: 0, - } - mockClient.query.mockResolvedValueOnce(mockQueryResult) - const result = await ecogestureService.deleteAllEcogestures() - expect(mockClient.destroy).toBeCalledTimes(3) - expect(result).toBe(true) - }) - it('shoud return true when no ecogestures stored', async () => { - const mockQueryResult: QueryResult<Ecogesture[]> = { - data: [], - bookmark: '', - next: false, - skip: 0, - } - mockClient.query.mockResolvedValueOnce(mockQueryResult) - const result = await ecogestureService.deleteAllEcogestures() - expect(result).toBe(true) - }) - it('shoud return false when error happened on deletion', async () => { - const mockQueryResult: QueryResult<Ecogesture[]> = { - data: ecogesturesData, - bookmark: '', - next: false, - skip: 0, - } - mockClient.destroy.mockRejectedValue(new Error()) - mockClient.query.mockResolvedValueOnce(mockQueryResult) - const result = await ecogestureService.deleteAllEcogestures() - expect(result).toBe(false) - }) - }) - - describe('filteredEcogestureList', () => { - describe('usage heating', () => { - it('shoud return ecogesture with electricity', async () => { - const mockEcogestureList: Ecogesture[] = ecogesturesHeatingData - const mockProfileType: ProfileType = { - ...profileData.profileType, - heating: IndividualOrCollective.INDIVIDUAL, - warmingFluid: FluidType.ELECTRICITY, - } - const result = EcogestureService.getEcogestureListByProfile( - mockEcogestureList, - mockProfileType - ) - expect(result).toEqual([mockEcogestureList[0], mockEcogestureList[2]]) - }) - it('shoud return ecogesture with gas', async () => { - const mockEcogestureList: Ecogesture[] = ecogesturesHeatingData - const mockProfileType: ProfileType = { - ...profileData.profileType, - heating: IndividualOrCollective.INDIVIDUAL, - warmingFluid: FluidType.GAS, - } - const result = EcogestureService.getEcogestureListByProfile( - mockEcogestureList, - mockProfileType - ) - expect(result).toEqual([mockEcogestureList[1], mockEcogestureList[2]]) - }) - it('shoud not return ecogesture when profile heating is collective', async () => { - const mockEcogestureList: Ecogesture[] = ecogesturesHeatingData - const mockProfileType: ProfileType = { - ...profileData.profileType, - heating: IndividualOrCollective.COLLECTIVE, - warmingFluid: FluidType.ELECTRICITY, - } - const result = EcogestureService.getEcogestureListByProfile( - mockEcogestureList, - mockProfileType - ) - expect(result).toEqual([]) - }) - }) - - describe('usage ECS', () => { - it('shoud return ecogesture with electricity', async () => { - const mockEcogestureList: Ecogesture[] = ecogesturesECSData - const mockProfileType: ProfileType = { - ...profileData.profileType, - hotWater: IndividualOrCollective.INDIVIDUAL, - hotWaterFluid: FluidType.ELECTRICITY, - } - const result = EcogestureService.getEcogestureListByProfile( - mockEcogestureList, - mockProfileType - ) - expect(result).toEqual([mockEcogestureList[0], mockEcogestureList[2]]) - }) - it('shoud return ecogesture with gas', async () => { - const mockEcogestureList: Ecogesture[] = ecogesturesECSData - const mockProfileType: ProfileType = { - ...profileData.profileType, - hotWater: IndividualOrCollective.INDIVIDUAL, - hotWaterFluid: FluidType.GAS, - } - const result = EcogestureService.getEcogestureListByProfile( - mockEcogestureList, - mockProfileType - ) - expect(result).toEqual([mockEcogestureList[1], mockEcogestureList[2]]) - }) - it('shoud not return ecogesture when profile warming is collective', async () => { - const mockEcogestureList: Ecogesture[] = ecogesturesECSData - const mockProfileType: ProfileType = { - ...profileData.profileType, - hotWater: IndividualOrCollective.COLLECTIVE, - hotWaterFluid: FluidType.ELECTRICITY, - } - const result = EcogestureService.getEcogestureListByProfile( - mockEcogestureList, - mockProfileType - ) - expect(result).toEqual([]) - }) - }) - - describe('usage COOKING', () => { - it('shoud return ecogesture with electricity', async () => { - const mockEcogestureList: Ecogesture[] = ecogesturesCookingData - const mockProfileType: ProfileType = { - ...profileData.profileType, - cookingFluid: FluidType.ELECTRICITY, - } - const result = EcogestureService.getEcogestureListByProfile( - mockEcogestureList, - mockProfileType - ) - expect(result).toEqual([mockEcogestureList[0], mockEcogestureList[2]]) - }) - it('shoud return ecogesture with gas', async () => { - const mockEcogestureList: Ecogesture[] = ecogesturesCookingData - const mockProfileType: ProfileType = { - ...profileData.profileType, - cookingFluid: FluidType.GAS, - } - const result = EcogestureService.getEcogestureListByProfile( - mockEcogestureList, - mockProfileType - ) - expect(result).toEqual([mockEcogestureList[1], mockEcogestureList[2]]) - }) - }) - - describe('usage COLD_WATER', () => { - it('shoud return all water ecogestures', async () => { - const mockEcogestureList: Ecogesture[] = ecogesturesColdWaterData - const mockProfileType: ProfileType = { - ...profileData.profileType, - coldWater: IndividualOrCollective.INDIVIDUAL, - } - const result = EcogestureService.getEcogestureListByProfile( - mockEcogestureList, - mockProfileType - ) - expect(result).toEqual(mockEcogestureList) - }) - it('shoud not return water ecogestures', async () => { - const mockEcogestureList: Ecogesture[] = ecogesturesColdWaterData - const mockProfileType: ProfileType = { - ...profileData.profileType, - coldWater: IndividualOrCollective.COLLECTIVE, - } - const result = EcogestureService.getEcogestureListByProfile( - mockEcogestureList, - mockProfileType - ) - expect(result).toEqual([]) - }) - }) - - describe('usage ELECTRICITY_SPECIFIC', () => { - it('shoud return all ecogestures', async () => { - const mockEcogestureList: Ecogesture[] = ecogesturesElecSpecificData - const mockProfileType: ProfileType = { - ...profileData.profileType, - } - const result = EcogestureService.getEcogestureListByProfile( - mockEcogestureList, - mockProfileType - ) - expect(result).toEqual(mockEcogestureList) - }) - }) - - describe('usage AIR_CONDITIONING', () => { - it('shoud not return ecogestures', async () => { - const mockEcogestureList: Ecogesture[] = ecogesturesAirConditioningData - const mockProfileType: ProfileType = { - ...profileData.profileType, - } - const result = EcogestureService.getEcogestureListByProfile( - mockEcogestureList, - mockProfileType - ) - expect(result).toEqual([]) - }) - }) - }) -}) +import { QueryResult } from 'cozy-client' +import { Ecogesture } from 'models' +import EcogestureService from './ecogesture.service' +import mockClient from '../../tests/__mocks__/client' +import { + ecogesturesAirConditioningData, + ecogesturesColdWaterData, + ecogesturesCookingData, + ecogesturesData, + ecogesturesECSData, + ecogesturesElecSpecificData, + ecogesturesHeatingData, +} from '../../tests/__mocks__/ecogesturesData.mock' +import { ProfileType } from 'models/profileType.model' +import { profileData } from '../../tests/__mocks__/profile.mock' +import { IndividualOrCollective } from 'enum/profileType.enum' +import { FluidType } from 'enum/fluid.enum' + +describe('Ecogesture service', () => { + const ecogestureService = new EcogestureService(mockClient) + + describe('getAllEcogestures', () => { + it('shoud return all ecogestures', async () => { + const mockQueryResult: QueryResult<Ecogesture[]> = { + data: ecogesturesData, + bookmark: '', + next: false, + skip: 0, + } + mockClient.query.mockResolvedValueOnce(mockQueryResult) + const result = await ecogestureService.getAllEcogestures() + expect(result).toEqual(ecogesturesData) + }) + it('shoud return empty array when no ecogestures stored', async () => { + const mockQueryResult: QueryResult<Ecogesture[]> = { + data: [], + bookmark: '', + next: false, + skip: 0, + } + mockClient.query.mockResolvedValueOnce(mockQueryResult) + const result = await ecogestureService.getAllEcogestures() + expect(result).toEqual([]) + }) + }) + + describe('deleteAllEcogestures', () => { + it('shoud return true when 3 ecogestures stored', async () => { + const mockQueryResult: QueryResult<Ecogesture[]> = { + data: ecogesturesData, + bookmark: '', + next: false, + skip: 0, + } + mockClient.query.mockResolvedValueOnce(mockQueryResult) + const result = await ecogestureService.deleteAllEcogestures() + expect(mockClient.destroy).toBeCalledTimes(3) + expect(result).toBe(true) + }) + it('shoud return true when no ecogestures stored', async () => { + const mockQueryResult: QueryResult<Ecogesture[]> = { + data: [], + bookmark: '', + next: false, + skip: 0, + } + mockClient.query.mockResolvedValueOnce(mockQueryResult) + const result = await ecogestureService.deleteAllEcogestures() + expect(result).toBe(true) + }) + it('shoud return false when error happened on deletion', async () => { + const mockQueryResult: QueryResult<Ecogesture[]> = { + data: ecogesturesData, + bookmark: '', + next: false, + skip: 0, + } + mockClient.destroy.mockRejectedValue(new Error()) + mockClient.query.mockResolvedValueOnce(mockQueryResult) + const result = await ecogestureService.deleteAllEcogestures() + expect(result).toBe(false) + }) + }) + + describe('filteredEcogestureList', () => { + describe('usage heating', () => { + it('shoud return ecogesture with electricity', async () => { + const mockEcogestureList: Ecogesture[] = ecogesturesHeatingData + const mockProfileType: ProfileType = { + ...profileData.profileType, + heating: IndividualOrCollective.INDIVIDUAL, + warmingFluid: FluidType.ELECTRICITY, + } + const result = EcogestureService.getEcogestureListByProfile( + mockEcogestureList, + mockProfileType + ) + expect(result).toEqual([mockEcogestureList[0], mockEcogestureList[2]]) + }) + it('shoud return ecogesture with gas', async () => { + const mockEcogestureList: Ecogesture[] = ecogesturesHeatingData + const mockProfileType: ProfileType = { + ...profileData.profileType, + heating: IndividualOrCollective.INDIVIDUAL, + warmingFluid: FluidType.GAS, + } + const result = EcogestureService.getEcogestureListByProfile( + mockEcogestureList, + mockProfileType + ) + expect(result).toEqual([mockEcogestureList[1], mockEcogestureList[2]]) + }) + it('shoud not return ecogesture when profile heating is collective', async () => { + const mockEcogestureList: Ecogesture[] = ecogesturesHeatingData + const mockProfileType: ProfileType = { + ...profileData.profileType, + heating: IndividualOrCollective.COLLECTIVE, + warmingFluid: FluidType.ELECTRICITY, + } + const result = EcogestureService.getEcogestureListByProfile( + mockEcogestureList, + mockProfileType + ) + expect(result).toEqual([]) + }) + }) + + describe('usage ECS', () => { + it('shoud return ecogesture with electricity', async () => { + const mockEcogestureList: Ecogesture[] = ecogesturesECSData + const mockProfileType: ProfileType = { + ...profileData.profileType, + hotWater: IndividualOrCollective.INDIVIDUAL, + hotWaterFluid: FluidType.ELECTRICITY, + } + const result = EcogestureService.getEcogestureListByProfile( + mockEcogestureList, + mockProfileType + ) + expect(result).toEqual([mockEcogestureList[0], mockEcogestureList[2]]) + }) + it('shoud return ecogesture with gas', async () => { + const mockEcogestureList: Ecogesture[] = ecogesturesECSData + const mockProfileType: ProfileType = { + ...profileData.profileType, + hotWater: IndividualOrCollective.INDIVIDUAL, + hotWaterFluid: FluidType.GAS, + } + const result = EcogestureService.getEcogestureListByProfile( + mockEcogestureList, + mockProfileType + ) + expect(result).toEqual([mockEcogestureList[1], mockEcogestureList[2]]) + }) + it('shoud not return ecogesture when profile warming is collective', async () => { + const mockEcogestureList: Ecogesture[] = ecogesturesECSData + const mockProfileType: ProfileType = { + ...profileData.profileType, + hotWater: IndividualOrCollective.COLLECTIVE, + hotWaterFluid: FluidType.ELECTRICITY, + } + const result = EcogestureService.getEcogestureListByProfile( + mockEcogestureList, + mockProfileType + ) + expect(result).toEqual([]) + }) + }) + + describe('usage COOKING', () => { + it('shoud return ecogesture with electricity', async () => { + const mockEcogestureList: Ecogesture[] = ecogesturesCookingData + const mockProfileType: ProfileType = { + ...profileData.profileType, + cookingFluid: FluidType.ELECTRICITY, + } + const result = EcogestureService.getEcogestureListByProfile( + mockEcogestureList, + mockProfileType + ) + expect(result).toEqual([mockEcogestureList[0], mockEcogestureList[2]]) + }) + it('shoud return ecogesture with gas', async () => { + const mockEcogestureList: Ecogesture[] = ecogesturesCookingData + const mockProfileType: ProfileType = { + ...profileData.profileType, + cookingFluid: FluidType.GAS, + } + const result = EcogestureService.getEcogestureListByProfile( + mockEcogestureList, + mockProfileType + ) + expect(result).toEqual([mockEcogestureList[1], mockEcogestureList[2]]) + }) + }) + + describe('usage COLD_WATER', () => { + it('shoud return all water ecogestures', async () => { + const mockEcogestureList: Ecogesture[] = ecogesturesColdWaterData + const mockProfileType: ProfileType = { + ...profileData.profileType, + coldWater: IndividualOrCollective.INDIVIDUAL, + } + const result = EcogestureService.getEcogestureListByProfile( + mockEcogestureList, + mockProfileType + ) + expect(result).toEqual(mockEcogestureList) + }) + it('shoud not return water ecogestures', async () => { + const mockEcogestureList: Ecogesture[] = ecogesturesColdWaterData + const mockProfileType: ProfileType = { + ...profileData.profileType, + coldWater: IndividualOrCollective.COLLECTIVE, + } + const result = EcogestureService.getEcogestureListByProfile( + mockEcogestureList, + mockProfileType + ) + expect(result).toEqual([]) + }) + }) + + describe('usage ELECTRICITY_SPECIFIC', () => { + it('shoud return all ecogestures', async () => { + const mockEcogestureList: Ecogesture[] = ecogesturesElecSpecificData + const mockProfileType: ProfileType = { + ...profileData.profileType, + } + const result = EcogestureService.getEcogestureListByProfile( + mockEcogestureList, + mockProfileType + ) + expect(result).toEqual(mockEcogestureList) + }) + }) + + describe('usage AIR_CONDITIONING', () => { + it('shoud not return ecogestures', async () => { + const mockEcogestureList: Ecogesture[] = ecogesturesAirConditioningData + const mockProfileType: ProfileType = { + ...profileData.profileType, + } + const result = EcogestureService.getEcogestureListByProfile( + mockEcogestureList, + mockProfileType + ) + expect(result).toEqual([]) + }) + }) + }) +}) diff --git a/src/services/exploration.service.spec.ts b/src/services/exploration.service.spec.ts index 6ebac45ff9c9b8d5228bf3f2503476a882f0cfb7..f202814b01f877dd44151c50e35d6cd2fe747f5f 100644 --- a/src/services/exploration.service.spec.ts +++ b/src/services/exploration.service.spec.ts @@ -6,13 +6,13 @@ import { UserExplorationUnlocked, UserExplorationDone, UserExplorationStarted, -} from '../../test/__mocks__/explorationData.mock' -import mockClient from '../../test/__mocks__/client' +} from '../../tests/__mocks__/explorationData.mock' +import mockClient from '../../tests/__mocks__/client' import ExplorationService from './exploration.service' import { userChallengeExplo1OnGoing, userChallengeExplo2OnGoing, -} from '../../test/__mocks__/userChallengeData.mock' +} from '../../tests/__mocks__/userChallengeData.mock' import { UserExplorationState } from 'enum/userExploration.enum' describe('Exploration service', () => { diff --git a/src/services/fluid.service.spec.ts b/src/services/fluid.service.spec.ts index 41db75fe81670f930a496755b7ffd6642129458f..f4c767f3ad54870f81da41c6f79374b99efb42e4 100644 --- a/src/services/fluid.service.spec.ts +++ b/src/services/fluid.service.spec.ts @@ -1,650 +1,650 @@ -import FluidService from './fluid.service' -import mockClient from '../../test/__mocks__/client' -import { accountsData } from '../../test/__mocks__/accountsData.mock' -import { konnectorsData } from '../../test/__mocks__/konnectorsData.mock' -import { triggersData } from '../../test/__mocks__/triggersData.mock' -import { triggerStateData } from '../../test/__mocks__/triggerStateData.mock' -import { DateTime } from 'luxon' -import { FluidState, FluidType } from 'enum/fluid.enum' -import { FluidStatus } from 'models' - -const mockGetAccountByType = jest.fn() -jest.mock('./account.service', () => { - return jest.fn(() => { - return { - getAccountByType: mockGetAccountByType, - } - }) -}) - -const mockGetKonnector = jest.fn() -jest.mock('./konnector.service', () => { - return jest.fn(() => { - return { - getKonnector: mockGetKonnector, - } - }) -}) - -const mockGetTrigger = jest.fn() -const mockFetchTriggerState = jest.fn() -jest.mock('./triggers.service', () => { - return jest.fn(() => { - return { - getTrigger: mockGetTrigger, - fetchTriggerState: mockFetchTriggerState, - } - }) -}) - -const mockFetchAllLastDateData = jest.fn() -jest.mock('./consumption.service', () => { - return jest.fn(() => { - return { - fetchAllLastDateData: mockFetchAllLastDateData, - } - }) -}) - -describe('FLuid service', () => { - const fluidService = new FluidService(mockClient) - - beforeEach(() => { - mockGetAccountByType.mockReset() - mockGetTrigger.mockReset() - mockFetchTriggerState.mockReset() - mockFetchAllLastDateData.mockReset() - }) - - describe('getFluidStatus method', () => { - it('shoud return fluid status for all fluids', async () => { - const mockLastDataDates: (DateTime | null)[] = [ - DateTime.local().setZone('utc', { - keepLocalTime: true, - }), - DateTime.local().setZone('utc', { - keepLocalTime: true, - }), - DateTime.local().setZone('utc', { - keepLocalTime: true, - }), - ] - const mockResult: FluidStatus[] = [ - { - fluidType: FluidType.ELECTRICITY, - status: FluidState.ERROR, - lastDataDate: mockLastDataDates[FluidType.ELECTRICITY], - connection: { - konnector: konnectorsData[0], - account: accountsData[0], - trigger: triggersData[0], - triggerState: triggerStateData, - shouldLaunchKonnector: false, - isUpdating: false, - konnectorConfig: { - name: 'Enedis', - oauth: true, - slug: 'enedisgrandlyon', - siteLink: 'https://mon-compte-client.enedis.fr/', - activation: 'https://mon-compte-particulier.enedis.fr/donnees/', - }, - }, - }, - { - fluidType: FluidType.WATER, - status: FluidState.ERROR, - lastDataDate: mockLastDataDates[FluidType.WATER], - connection: { - konnector: konnectorsData[1], - account: accountsData[1], - trigger: triggersData[1], - triggerState: triggerStateData, - shouldLaunchKonnector: false, - isUpdating: false, - konnectorConfig: { - name: 'Eau du Grand Lyon', - oauth: false, - slug: 'eglgrandlyon', - siteLink: 'https://agence.eaudugrandlyon.com/inscription.aspx', - activation: '', - }, - }, - }, - { - fluidType: FluidType.GAS, - status: FluidState.ERROR, - lastDataDate: mockLastDataDates[FluidType.GAS], - connection: { - konnector: konnectorsData[2], - account: accountsData[2], - trigger: triggersData[2], - triggerState: triggerStateData, - shouldLaunchKonnector: false, - isUpdating: false, - konnectorConfig: { - name: 'GRDF', - oauth: true, - slug: 'grdfgrandlyon', - siteLink: 'https://monespace.grdf.fr/monespace/connexion', - activation: '', - }, - }, - }, - ] - mockGetAccountByType - .mockResolvedValueOnce(accountsData[0]) - .mockResolvedValueOnce(accountsData[1]) - .mockResolvedValueOnce(accountsData[2]) - mockGetKonnector - .mockResolvedValueOnce(konnectorsData[0]) - .mockResolvedValueOnce(konnectorsData[1]) - .mockResolvedValueOnce(konnectorsData[2]) - mockGetTrigger - .mockResolvedValueOnce(triggersData[0]) - .mockResolvedValueOnce(triggersData[1]) - .mockResolvedValueOnce(triggersData[2]) - mockFetchTriggerState.mockResolvedValue(triggerStateData) - mockFetchAllLastDateData.mockResolvedValue(mockLastDataDates) - const result: FluidStatus[] = await fluidService.getFluidStatus() - expect(result).toEqual(mockResult) - }) - - it('shoud return fluid status with NOT_CONNECTED status when no accounts', async () => { - const mockLastDataDates: (DateTime | null)[] = [ - DateTime.local().setZone('utc', { - keepLocalTime: true, - }), - DateTime.local().setZone('utc', { - keepLocalTime: true, - }), - DateTime.local().setZone('utc', { - keepLocalTime: true, - }), - ] - const mockResult: FluidStatus[] = [ - { - fluidType: FluidType.ELECTRICITY, - status: FluidState.NOT_CONNECTED, - lastDataDate: mockLastDataDates[FluidType.ELECTRICITY], - connection: { - konnector: konnectorsData[0], - account: null, - trigger: null, - triggerState: null, - shouldLaunchKonnector: false, - isUpdating: false, - konnectorConfig: { - name: 'Enedis', - oauth: true, - slug: 'enedisgrandlyon', - siteLink: 'https://mon-compte-client.enedis.fr/', - activation: 'https://mon-compte-particulier.enedis.fr/donnees/', - }, - }, - }, - { - fluidType: FluidType.WATER, - status: FluidState.NOT_CONNECTED, - lastDataDate: mockLastDataDates[FluidType.WATER], - connection: { - konnector: konnectorsData[1], - account: null, - trigger: null, - triggerState: null, - shouldLaunchKonnector: false, - isUpdating: false, - konnectorConfig: { - name: 'Eau du Grand Lyon', - oauth: false, - slug: 'eglgrandlyon', - siteLink: 'https://agence.eaudugrandlyon.com/inscription.aspx', - activation: '', - }, - }, - }, - { - fluidType: FluidType.GAS, - status: FluidState.NOT_CONNECTED, - lastDataDate: mockLastDataDates[FluidType.GAS], - connection: { - konnector: konnectorsData[2], - account: null, - trigger: null, - triggerState: null, - shouldLaunchKonnector: false, - isUpdating: false, - konnectorConfig: { - name: 'GRDF', - oauth: true, - slug: 'grdfgrandlyon', - siteLink: 'https://monespace.grdf.fr/monespace/connexion', - activation: '', - }, - }, - }, - ] - mockGetAccountByType - .mockResolvedValueOnce(null) - .mockResolvedValueOnce(null) - .mockResolvedValueOnce(null) - mockGetKonnector - .mockResolvedValueOnce(konnectorsData[0]) - .mockResolvedValueOnce(konnectorsData[1]) - .mockResolvedValueOnce(konnectorsData[2]) - mockGetTrigger - .mockResolvedValueOnce(triggersData[0]) - .mockResolvedValueOnce(triggersData[1]) - .mockResolvedValueOnce(triggersData[2]) - mockFetchTriggerState.mockResolvedValue(triggerStateData) - mockFetchAllLastDateData.mockResolvedValue(mockLastDataDates) - const result: FluidStatus[] = await fluidService.getFluidStatus() - expect(result).toEqual(mockResult) - }) - - it('shoud return fluid status with KONNECTOR_NOT_FOUND status when no konnector', async () => { - const mockLastDataDates: (DateTime | null)[] = [ - DateTime.local().setZone('utc', { - keepLocalTime: true, - }), - DateTime.local().setZone('utc', { - keepLocalTime: true, - }), - DateTime.local().setZone('utc', { - keepLocalTime: true, - }), - ] - const mockResult: FluidStatus[] = [ - { - fluidType: FluidType.ELECTRICITY, - status: FluidState.KONNECTOR_NOT_FOUND, - lastDataDate: mockLastDataDates[FluidType.ELECTRICITY], - connection: { - konnector: null, - account: accountsData[0], - trigger: null, - triggerState: null, - shouldLaunchKonnector: false, - isUpdating: false, - konnectorConfig: { - name: 'Enedis', - oauth: true, - slug: 'enedisgrandlyon', - siteLink: 'https://mon-compte-client.enedis.fr/', - activation: 'https://mon-compte-particulier.enedis.fr/donnees/', - }, - }, - }, - { - fluidType: FluidType.WATER, - status: FluidState.KONNECTOR_NOT_FOUND, - lastDataDate: mockLastDataDates[FluidType.WATER], - connection: { - konnector: null, - account: accountsData[1], - trigger: null, - triggerState: null, - shouldLaunchKonnector: false, - isUpdating: false, - konnectorConfig: { - name: 'Eau du Grand Lyon', - oauth: false, - slug: 'eglgrandlyon', - siteLink: 'https://agence.eaudugrandlyon.com/inscription.aspx', - activation: '', - }, - }, - }, - { - fluidType: FluidType.GAS, - status: FluidState.KONNECTOR_NOT_FOUND, - lastDataDate: mockLastDataDates[FluidType.GAS], - connection: { - konnector: null, - account: accountsData[2], - trigger: null, - triggerState: null, - shouldLaunchKonnector: false, - isUpdating: false, - konnectorConfig: { - name: 'GRDF', - oauth: true, - slug: 'grdfgrandlyon', - siteLink: 'https://monespace.grdf.fr/monespace/connexion', - activation: '', - }, - }, - }, - ] - mockGetAccountByType - .mockResolvedValueOnce(accountsData[0]) - .mockResolvedValueOnce(accountsData[1]) - .mockResolvedValueOnce(accountsData[2]) - mockGetKonnector - .mockResolvedValueOnce(null) - .mockResolvedValueOnce(null) - .mockResolvedValueOnce(null) - mockGetTrigger - .mockResolvedValueOnce(triggersData[0]) - .mockResolvedValueOnce(triggersData[1]) - .mockResolvedValueOnce(triggersData[2]) - mockFetchTriggerState.mockResolvedValue(triggerStateData) - mockFetchAllLastDateData.mockResolvedValue(mockLastDataDates) - const result: FluidStatus[] = await fluidService.getFluidStatus() - expect(result).toEqual(mockResult) - }) - - it('shoud return fluid status with NOT_CONNECTED status when no triggers', async () => { - const mockLastDataDates: (DateTime | null)[] = [ - DateTime.local().setZone('utc', { - keepLocalTime: true, - }), - DateTime.local().setZone('utc', { - keepLocalTime: true, - }), - DateTime.local().setZone('utc', { - keepLocalTime: true, - }), - ] - const mockResult: FluidStatus[] = [ - { - fluidType: FluidType.ELECTRICITY, - status: FluidState.NOT_CONNECTED, - lastDataDate: mockLastDataDates[FluidType.ELECTRICITY], - connection: { - konnector: konnectorsData[0], - account: accountsData[0], - trigger: null, - triggerState: null, - shouldLaunchKonnector: false, - isUpdating: false, - konnectorConfig: { - name: 'Enedis', - oauth: true, - slug: 'enedisgrandlyon', - siteLink: 'https://mon-compte-client.enedis.fr/', - activation: 'https://mon-compte-particulier.enedis.fr/donnees/', - }, - }, - }, - { - fluidType: FluidType.WATER, - status: FluidState.NOT_CONNECTED, - lastDataDate: mockLastDataDates[FluidType.WATER], - connection: { - konnector: konnectorsData[1], - account: accountsData[1], - trigger: null, - triggerState: null, - shouldLaunchKonnector: false, - isUpdating: false, - konnectorConfig: { - name: 'Eau du Grand Lyon', - oauth: false, - slug: 'eglgrandlyon', - siteLink: 'https://agence.eaudugrandlyon.com/inscription.aspx', - activation: '', - }, - }, - }, - { - fluidType: FluidType.GAS, - status: FluidState.NOT_CONNECTED, - lastDataDate: mockLastDataDates[FluidType.GAS], - connection: { - konnector: konnectorsData[2], - account: accountsData[2], - trigger: null, - triggerState: null, - shouldLaunchKonnector: false, - isUpdating: false, - konnectorConfig: { - name: 'GRDF', - oauth: true, - slug: 'grdfgrandlyon', - siteLink: 'https://monespace.grdf.fr/monespace/connexion', - activation: '', - }, - }, - }, - ] - mockGetAccountByType - .mockResolvedValueOnce(accountsData[0]) - .mockResolvedValueOnce(accountsData[1]) - .mockResolvedValueOnce(accountsData[2]) - mockGetKonnector - .mockResolvedValueOnce(konnectorsData[0]) - .mockResolvedValueOnce(konnectorsData[1]) - .mockResolvedValueOnce(konnectorsData[2]) - mockGetTrigger - .mockResolvedValueOnce(null) - .mockResolvedValueOnce(null) - .mockResolvedValueOnce(null) - mockFetchTriggerState.mockResolvedValue(triggerStateData) - mockFetchAllLastDateData.mockResolvedValue(mockLastDataDates) - const result: FluidStatus[] = await fluidService.getFluidStatus() - expect(result).toEqual(mockResult) - }) - - it('shoud return fluid status with null laste date for water and gaz', async () => { - const mockLastDataDates: (DateTime | null)[] = [ - DateTime.local(), - null, - null, - ] - const mockResult: FluidStatus[] = [ - { - fluidType: FluidType.ELECTRICITY, - status: FluidState.ERROR, - lastDataDate: mockLastDataDates[FluidType.ELECTRICITY], - connection: { - konnector: konnectorsData[0], - account: accountsData[0], - trigger: triggersData[0], - triggerState: triggerStateData, - shouldLaunchKonnector: false, - isUpdating: false, - konnectorConfig: { - name: 'Enedis', - oauth: true, - slug: 'enedisgrandlyon', - siteLink: 'https://mon-compte-client.enedis.fr/', - activation: 'https://mon-compte-particulier.enedis.fr/donnees/', - }, - }, - }, - { - fluidType: FluidType.WATER, - status: FluidState.NOT_CONNECTED, - lastDataDate: null, - connection: { - konnector: konnectorsData[1], - account: accountsData[1], - trigger: triggersData[1], - triggerState: null, - shouldLaunchKonnector: false, - isUpdating: false, - konnectorConfig: { - name: 'Eau du Grand Lyon', - oauth: false, - slug: 'eglgrandlyon', - siteLink: 'https://agence.eaudugrandlyon.com/inscription.aspx', - activation: '', - }, - }, - }, - { - fluidType: FluidType.GAS, - status: FluidState.NOT_CONNECTED, - lastDataDate: null, - connection: { - konnector: konnectorsData[2], - account: accountsData[2], - trigger: triggersData[2], - triggerState: null, - shouldLaunchKonnector: false, - isUpdating: false, - konnectorConfig: { - name: 'GRDF', - oauth: true, - slug: 'grdfgrandlyon', - siteLink: 'https://monespace.grdf.fr/monespace/connexion', - activation: '', - }, - }, - }, - ] - mockGetAccountByType - .mockResolvedValueOnce(accountsData[0]) - .mockResolvedValueOnce(accountsData[1]) - .mockResolvedValueOnce(accountsData[2]) - mockGetKonnector - .mockResolvedValueOnce(konnectorsData[0]) - .mockResolvedValueOnce(konnectorsData[1]) - .mockResolvedValueOnce(konnectorsData[2]) - mockGetTrigger - .mockResolvedValueOnce(triggersData[0]) - .mockResolvedValueOnce(triggersData[1]) - .mockResolvedValueOnce(triggersData[2]) - mockFetchTriggerState - .mockResolvedValueOnce(triggerStateData) - .mockResolvedValueOnce(null) - .mockResolvedValueOnce(null) - mockFetchAllLastDateData.mockResolvedValue(mockLastDataDates) - const result: FluidStatus[] = await fluidService.getFluidStatus() - expect(result).toEqual(mockResult) - }) - }) - - describe('getOldFluidData method', () => { - it('shoud return Electricity as old fluid', async () => { - const mockFluidStatus: FluidStatus[] = [ - { - fluidType: FluidType.ELECTRICITY, - status: FluidState.DONE, - lastDataDate: DateTime.fromISO('2020-01-01').setZone('utc', { - keepLocalTime: true, - }), - connection: { - konnector: konnectorsData[0], - account: accountsData[0], - trigger: triggersData[0], - triggerState: triggerStateData, - shouldLaunchKonnector: false, - isUpdating: false, - konnectorConfig: { - name: 'Enedis', - oauth: true, - slug: 'enedisgrandlyon', - siteLink: 'https://mon-compte-client.enedis.fr/', - activation: 'https://mon-compte-particulier.enedis.fr/donnees/', - }, - }, - }, - ] - const result: FluidType[] = await FluidService.getOldFluidData( - mockFluidStatus - ) - expect(result).toEqual([FluidType.ELECTRICITY]) - }) - - it('shoud return empty array as lastdatadate < 5 days', async () => { - const mockFluidStatus: FluidStatus[] = [ - { - fluidType: FluidType.ELECTRICITY, - status: FluidState.DONE, - lastDataDate: DateTime.local() - .minus({ day: 1 }) - .setZone('utc', { - keepLocalTime: true, - }), - connection: { - konnector: konnectorsData[0], - account: accountsData[0], - trigger: triggersData[0], - triggerState: triggerStateData, - shouldLaunchKonnector: false, - isUpdating: false, - konnectorConfig: { - name: 'Enedis', - oauth: true, - slug: 'enedisgrandlyon', - siteLink: 'https://mon-compte-client.enedis.fr/', - activation: 'https://mon-compte-particulier.enedis.fr/donnees/', - }, - }, - }, - ] - const result: FluidType[] = await FluidService.getOldFluidData( - mockFluidStatus - ) - expect(result).toEqual([]) - }) - - it('shoud return empty array as status is NOT_CONNECTED', async () => { - const mockFluidStatus: FluidStatus[] = [ - { - fluidType: FluidType.ELECTRICITY, - status: FluidState.NOT_CONNECTED, - lastDataDate: DateTime.fromISO('2020-01-01').setZone('utc', { - keepLocalTime: true, - }), - connection: { - konnector: konnectorsData[0], - account: accountsData[0], - trigger: triggersData[0], - triggerState: triggerStateData, - shouldLaunchKonnector: false, - isUpdating: false, - konnectorConfig: { - name: 'Enedis', - oauth: true, - slug: 'enedisgrandlyon', - siteLink: 'https://mon-compte-client.enedis.fr/', - activation: 'https://mon-compte-particulier.enedis.fr/donnees/', - }, - }, - }, - ] - const result: FluidType[] = await FluidService.getOldFluidData( - mockFluidStatus - ) - expect(result).toEqual([]) - }) - - it('shoud return empty array as status is KONNECTOR_NOT_FOUND', async () => { - const mockFluidStatus: FluidStatus[] = [ - { - fluidType: FluidType.ELECTRICITY, - status: FluidState.KONNECTOR_NOT_FOUND, - lastDataDate: DateTime.fromISO('2020-01-01').setZone('utc', { - keepLocalTime: true, - }), - connection: { - konnector: konnectorsData[0], - account: accountsData[0], - trigger: triggersData[0], - triggerState: triggerStateData, - shouldLaunchKonnector: false, - isUpdating: false, - konnectorConfig: { - name: 'Enedis', - oauth: true, - slug: 'enedisgrandlyon', - siteLink: 'https://mon-compte-client.enedis.fr/', - activation: 'https://mon-compte-particulier.enedis.fr/donnees/', - }, - }, - }, - ] - const result: FluidType[] = await FluidService.getOldFluidData( - mockFluidStatus - ) - expect(result).toEqual([]) - }) - - it('shoud return empty array', async () => { - const result: FluidType[] = await FluidService.getOldFluidData([]) - expect(result).toEqual([]) - }) - }) -}) +import FluidService from './fluid.service' +import mockClient from '../../tests/__mocks__/client' +import { accountsData } from '../../tests/__mocks__/accountsData.mock' +import { konnectorsData } from '../../tests/__mocks__/konnectorsData.mock' +import { triggersData } from '../../tests/__mocks__/triggersData.mock' +import { triggerStateData } from '../../tests/__mocks__/triggerStateData.mock' +import { DateTime } from 'luxon' +import { FluidState, FluidType } from 'enum/fluid.enum' +import { FluidStatus } from 'models' + +const mockGetAccountByType = jest.fn() +jest.mock('./account.service', () => { + return jest.fn(() => { + return { + getAccountByType: mockGetAccountByType, + } + }) +}) + +const mockGetKonnector = jest.fn() +jest.mock('./konnector.service', () => { + return jest.fn(() => { + return { + getKonnector: mockGetKonnector, + } + }) +}) + +const mockGetTrigger = jest.fn() +const mockFetchTriggerState = jest.fn() +jest.mock('./triggers.service', () => { + return jest.fn(() => { + return { + getTrigger: mockGetTrigger, + fetchTriggerState: mockFetchTriggerState, + } + }) +}) + +const mockFetchAllLastDateData = jest.fn() +jest.mock('./consumption.service', () => { + return jest.fn(() => { + return { + fetchAllLastDateData: mockFetchAllLastDateData, + } + }) +}) + +describe('FLuid service', () => { + const fluidService = new FluidService(mockClient) + + beforeEach(() => { + mockGetAccountByType.mockReset() + mockGetTrigger.mockReset() + mockFetchTriggerState.mockReset() + mockFetchAllLastDateData.mockReset() + }) + + describe('getFluidStatus method', () => { + it('shoud return fluid status for all fluids', async () => { + const mockLastDataDates: (DateTime | null)[] = [ + DateTime.local().setZone('utc', { + keepLocalTime: true, + }), + DateTime.local().setZone('utc', { + keepLocalTime: true, + }), + DateTime.local().setZone('utc', { + keepLocalTime: true, + }), + ] + const mockResult: FluidStatus[] = [ + { + fluidType: FluidType.ELECTRICITY, + status: FluidState.ERROR, + lastDataDate: mockLastDataDates[FluidType.ELECTRICITY], + connection: { + konnector: konnectorsData[0], + account: accountsData[0], + trigger: triggersData[0], + triggerState: triggerStateData, + shouldLaunchKonnector: false, + isUpdating: false, + konnectorConfig: { + name: 'Enedis', + oauth: true, + slug: 'enedisgrandlyon', + siteLink: 'https://mon-compte-client.enedis.fr/', + activation: 'https://mon-compte-particulier.enedis.fr/donnees/', + }, + }, + }, + { + fluidType: FluidType.WATER, + status: FluidState.ERROR, + lastDataDate: mockLastDataDates[FluidType.WATER], + connection: { + konnector: konnectorsData[1], + account: accountsData[1], + trigger: triggersData[1], + triggerState: triggerStateData, + shouldLaunchKonnector: false, + isUpdating: false, + konnectorConfig: { + name: 'Eau du Grand Lyon', + oauth: false, + slug: 'eglgrandlyon', + siteLink: 'https://agence.eaudugrandlyon.com/inscription.aspx', + activation: '', + }, + }, + }, + { + fluidType: FluidType.GAS, + status: FluidState.ERROR, + lastDataDate: mockLastDataDates[FluidType.GAS], + connection: { + konnector: konnectorsData[2], + account: accountsData[2], + trigger: triggersData[2], + triggerState: triggerStateData, + shouldLaunchKonnector: false, + isUpdating: false, + konnectorConfig: { + name: 'GRDF', + oauth: true, + slug: 'grdfgrandlyon', + siteLink: 'https://monespace.grdf.fr/monespace/connexion', + activation: '', + }, + }, + }, + ] + mockGetAccountByType + .mockResolvedValueOnce(accountsData[0]) + .mockResolvedValueOnce(accountsData[1]) + .mockResolvedValueOnce(accountsData[2]) + mockGetKonnector + .mockResolvedValueOnce(konnectorsData[0]) + .mockResolvedValueOnce(konnectorsData[1]) + .mockResolvedValueOnce(konnectorsData[2]) + mockGetTrigger + .mockResolvedValueOnce(triggersData[0]) + .mockResolvedValueOnce(triggersData[1]) + .mockResolvedValueOnce(triggersData[2]) + mockFetchTriggerState.mockResolvedValue(triggerStateData) + mockFetchAllLastDateData.mockResolvedValue(mockLastDataDates) + const result: FluidStatus[] = await fluidService.getFluidStatus() + expect(result).toEqual(mockResult) + }) + + it('shoud return fluid status with NOT_CONNECTED status when no accounts', async () => { + const mockLastDataDates: (DateTime | null)[] = [ + DateTime.local().setZone('utc', { + keepLocalTime: true, + }), + DateTime.local().setZone('utc', { + keepLocalTime: true, + }), + DateTime.local().setZone('utc', { + keepLocalTime: true, + }), + ] + const mockResult: FluidStatus[] = [ + { + fluidType: FluidType.ELECTRICITY, + status: FluidState.NOT_CONNECTED, + lastDataDate: mockLastDataDates[FluidType.ELECTRICITY], + connection: { + konnector: konnectorsData[0], + account: null, + trigger: null, + triggerState: null, + shouldLaunchKonnector: false, + isUpdating: false, + konnectorConfig: { + name: 'Enedis', + oauth: true, + slug: 'enedisgrandlyon', + siteLink: 'https://mon-compte-client.enedis.fr/', + activation: 'https://mon-compte-particulier.enedis.fr/donnees/', + }, + }, + }, + { + fluidType: FluidType.WATER, + status: FluidState.NOT_CONNECTED, + lastDataDate: mockLastDataDates[FluidType.WATER], + connection: { + konnector: konnectorsData[1], + account: null, + trigger: null, + triggerState: null, + shouldLaunchKonnector: false, + isUpdating: false, + konnectorConfig: { + name: 'Eau du Grand Lyon', + oauth: false, + slug: 'eglgrandlyon', + siteLink: 'https://agence.eaudugrandlyon.com/inscription.aspx', + activation: '', + }, + }, + }, + { + fluidType: FluidType.GAS, + status: FluidState.NOT_CONNECTED, + lastDataDate: mockLastDataDates[FluidType.GAS], + connection: { + konnector: konnectorsData[2], + account: null, + trigger: null, + triggerState: null, + shouldLaunchKonnector: false, + isUpdating: false, + konnectorConfig: { + name: 'GRDF', + oauth: true, + slug: 'grdfgrandlyon', + siteLink: 'https://monespace.grdf.fr/monespace/connexion', + activation: '', + }, + }, + }, + ] + mockGetAccountByType + .mockResolvedValueOnce(null) + .mockResolvedValueOnce(null) + .mockResolvedValueOnce(null) + mockGetKonnector + .mockResolvedValueOnce(konnectorsData[0]) + .mockResolvedValueOnce(konnectorsData[1]) + .mockResolvedValueOnce(konnectorsData[2]) + mockGetTrigger + .mockResolvedValueOnce(triggersData[0]) + .mockResolvedValueOnce(triggersData[1]) + .mockResolvedValueOnce(triggersData[2]) + mockFetchTriggerState.mockResolvedValue(triggerStateData) + mockFetchAllLastDateData.mockResolvedValue(mockLastDataDates) + const result: FluidStatus[] = await fluidService.getFluidStatus() + expect(result).toEqual(mockResult) + }) + + it('shoud return fluid status with KONNECTOR_NOT_FOUND status when no konnector', async () => { + const mockLastDataDates: (DateTime | null)[] = [ + DateTime.local().setZone('utc', { + keepLocalTime: true, + }), + DateTime.local().setZone('utc', { + keepLocalTime: true, + }), + DateTime.local().setZone('utc', { + keepLocalTime: true, + }), + ] + const mockResult: FluidStatus[] = [ + { + fluidType: FluidType.ELECTRICITY, + status: FluidState.KONNECTOR_NOT_FOUND, + lastDataDate: mockLastDataDates[FluidType.ELECTRICITY], + connection: { + konnector: null, + account: accountsData[0], + trigger: null, + triggerState: null, + shouldLaunchKonnector: false, + isUpdating: false, + konnectorConfig: { + name: 'Enedis', + oauth: true, + slug: 'enedisgrandlyon', + siteLink: 'https://mon-compte-client.enedis.fr/', + activation: 'https://mon-compte-particulier.enedis.fr/donnees/', + }, + }, + }, + { + fluidType: FluidType.WATER, + status: FluidState.KONNECTOR_NOT_FOUND, + lastDataDate: mockLastDataDates[FluidType.WATER], + connection: { + konnector: null, + account: accountsData[1], + trigger: null, + triggerState: null, + shouldLaunchKonnector: false, + isUpdating: false, + konnectorConfig: { + name: 'Eau du Grand Lyon', + oauth: false, + slug: 'eglgrandlyon', + siteLink: 'https://agence.eaudugrandlyon.com/inscription.aspx', + activation: '', + }, + }, + }, + { + fluidType: FluidType.GAS, + status: FluidState.KONNECTOR_NOT_FOUND, + lastDataDate: mockLastDataDates[FluidType.GAS], + connection: { + konnector: null, + account: accountsData[2], + trigger: null, + triggerState: null, + shouldLaunchKonnector: false, + isUpdating: false, + konnectorConfig: { + name: 'GRDF', + oauth: true, + slug: 'grdfgrandlyon', + siteLink: 'https://monespace.grdf.fr/monespace/connexion', + activation: '', + }, + }, + }, + ] + mockGetAccountByType + .mockResolvedValueOnce(accountsData[0]) + .mockResolvedValueOnce(accountsData[1]) + .mockResolvedValueOnce(accountsData[2]) + mockGetKonnector + .mockResolvedValueOnce(null) + .mockResolvedValueOnce(null) + .mockResolvedValueOnce(null) + mockGetTrigger + .mockResolvedValueOnce(triggersData[0]) + .mockResolvedValueOnce(triggersData[1]) + .mockResolvedValueOnce(triggersData[2]) + mockFetchTriggerState.mockResolvedValue(triggerStateData) + mockFetchAllLastDateData.mockResolvedValue(mockLastDataDates) + const result: FluidStatus[] = await fluidService.getFluidStatus() + expect(result).toEqual(mockResult) + }) + + it('shoud return fluid status with NOT_CONNECTED status when no triggers', async () => { + const mockLastDataDates: (DateTime | null)[] = [ + DateTime.local().setZone('utc', { + keepLocalTime: true, + }), + DateTime.local().setZone('utc', { + keepLocalTime: true, + }), + DateTime.local().setZone('utc', { + keepLocalTime: true, + }), + ] + const mockResult: FluidStatus[] = [ + { + fluidType: FluidType.ELECTRICITY, + status: FluidState.NOT_CONNECTED, + lastDataDate: mockLastDataDates[FluidType.ELECTRICITY], + connection: { + konnector: konnectorsData[0], + account: accountsData[0], + trigger: null, + triggerState: null, + shouldLaunchKonnector: false, + isUpdating: false, + konnectorConfig: { + name: 'Enedis', + oauth: true, + slug: 'enedisgrandlyon', + siteLink: 'https://mon-compte-client.enedis.fr/', + activation: 'https://mon-compte-particulier.enedis.fr/donnees/', + }, + }, + }, + { + fluidType: FluidType.WATER, + status: FluidState.NOT_CONNECTED, + lastDataDate: mockLastDataDates[FluidType.WATER], + connection: { + konnector: konnectorsData[1], + account: accountsData[1], + trigger: null, + triggerState: null, + shouldLaunchKonnector: false, + isUpdating: false, + konnectorConfig: { + name: 'Eau du Grand Lyon', + oauth: false, + slug: 'eglgrandlyon', + siteLink: 'https://agence.eaudugrandlyon.com/inscription.aspx', + activation: '', + }, + }, + }, + { + fluidType: FluidType.GAS, + status: FluidState.NOT_CONNECTED, + lastDataDate: mockLastDataDates[FluidType.GAS], + connection: { + konnector: konnectorsData[2], + account: accountsData[2], + trigger: null, + triggerState: null, + shouldLaunchKonnector: false, + isUpdating: false, + konnectorConfig: { + name: 'GRDF', + oauth: true, + slug: 'grdfgrandlyon', + siteLink: 'https://monespace.grdf.fr/monespace/connexion', + activation: '', + }, + }, + }, + ] + mockGetAccountByType + .mockResolvedValueOnce(accountsData[0]) + .mockResolvedValueOnce(accountsData[1]) + .mockResolvedValueOnce(accountsData[2]) + mockGetKonnector + .mockResolvedValueOnce(konnectorsData[0]) + .mockResolvedValueOnce(konnectorsData[1]) + .mockResolvedValueOnce(konnectorsData[2]) + mockGetTrigger + .mockResolvedValueOnce(null) + .mockResolvedValueOnce(null) + .mockResolvedValueOnce(null) + mockFetchTriggerState.mockResolvedValue(triggerStateData) + mockFetchAllLastDateData.mockResolvedValue(mockLastDataDates) + const result: FluidStatus[] = await fluidService.getFluidStatus() + expect(result).toEqual(mockResult) + }) + + it('shoud return fluid status with null laste date for water and gaz', async () => { + const mockLastDataDates: (DateTime | null)[] = [ + DateTime.local(), + null, + null, + ] + const mockResult: FluidStatus[] = [ + { + fluidType: FluidType.ELECTRICITY, + status: FluidState.ERROR, + lastDataDate: mockLastDataDates[FluidType.ELECTRICITY], + connection: { + konnector: konnectorsData[0], + account: accountsData[0], + trigger: triggersData[0], + triggerState: triggerStateData, + shouldLaunchKonnector: false, + isUpdating: false, + konnectorConfig: { + name: 'Enedis', + oauth: true, + slug: 'enedisgrandlyon', + siteLink: 'https://mon-compte-client.enedis.fr/', + activation: 'https://mon-compte-particulier.enedis.fr/donnees/', + }, + }, + }, + { + fluidType: FluidType.WATER, + status: FluidState.NOT_CONNECTED, + lastDataDate: null, + connection: { + konnector: konnectorsData[1], + account: accountsData[1], + trigger: triggersData[1], + triggerState: null, + shouldLaunchKonnector: false, + isUpdating: false, + konnectorConfig: { + name: 'Eau du Grand Lyon', + oauth: false, + slug: 'eglgrandlyon', + siteLink: 'https://agence.eaudugrandlyon.com/inscription.aspx', + activation: '', + }, + }, + }, + { + fluidType: FluidType.GAS, + status: FluidState.NOT_CONNECTED, + lastDataDate: null, + connection: { + konnector: konnectorsData[2], + account: accountsData[2], + trigger: triggersData[2], + triggerState: null, + shouldLaunchKonnector: false, + isUpdating: false, + konnectorConfig: { + name: 'GRDF', + oauth: true, + slug: 'grdfgrandlyon', + siteLink: 'https://monespace.grdf.fr/monespace/connexion', + activation: '', + }, + }, + }, + ] + mockGetAccountByType + .mockResolvedValueOnce(accountsData[0]) + .mockResolvedValueOnce(accountsData[1]) + .mockResolvedValueOnce(accountsData[2]) + mockGetKonnector + .mockResolvedValueOnce(konnectorsData[0]) + .mockResolvedValueOnce(konnectorsData[1]) + .mockResolvedValueOnce(konnectorsData[2]) + mockGetTrigger + .mockResolvedValueOnce(triggersData[0]) + .mockResolvedValueOnce(triggersData[1]) + .mockResolvedValueOnce(triggersData[2]) + mockFetchTriggerState + .mockResolvedValueOnce(triggerStateData) + .mockResolvedValueOnce(null) + .mockResolvedValueOnce(null) + mockFetchAllLastDateData.mockResolvedValue(mockLastDataDates) + const result: FluidStatus[] = await fluidService.getFluidStatus() + expect(result).toEqual(mockResult) + }) + }) + + describe('getOldFluidData method', () => { + it('shoud return Electricity as old fluid', async () => { + const mockFluidStatus: FluidStatus[] = [ + { + fluidType: FluidType.ELECTRICITY, + status: FluidState.DONE, + lastDataDate: DateTime.fromISO('2020-01-01').setZone('utc', { + keepLocalTime: true, + }), + connection: { + konnector: konnectorsData[0], + account: accountsData[0], + trigger: triggersData[0], + triggerState: triggerStateData, + shouldLaunchKonnector: false, + isUpdating: false, + konnectorConfig: { + name: 'Enedis', + oauth: true, + slug: 'enedisgrandlyon', + siteLink: 'https://mon-compte-client.enedis.fr/', + activation: 'https://mon-compte-particulier.enedis.fr/donnees/', + }, + }, + }, + ] + const result: FluidType[] = await FluidService.getOldFluidData( + mockFluidStatus + ) + expect(result).toEqual([FluidType.ELECTRICITY]) + }) + + it('shoud return empty array as lastdatadate < 5 days', async () => { + const mockFluidStatus: FluidStatus[] = [ + { + fluidType: FluidType.ELECTRICITY, + status: FluidState.DONE, + lastDataDate: DateTime.local() + .minus({ day: 1 }) + .setZone('utc', { + keepLocalTime: true, + }), + connection: { + konnector: konnectorsData[0], + account: accountsData[0], + trigger: triggersData[0], + triggerState: triggerStateData, + shouldLaunchKonnector: false, + isUpdating: false, + konnectorConfig: { + name: 'Enedis', + oauth: true, + slug: 'enedisgrandlyon', + siteLink: 'https://mon-compte-client.enedis.fr/', + activation: 'https://mon-compte-particulier.enedis.fr/donnees/', + }, + }, + }, + ] + const result: FluidType[] = await FluidService.getOldFluidData( + mockFluidStatus + ) + expect(result).toEqual([]) + }) + + it('shoud return empty array as status is NOT_CONNECTED', async () => { + const mockFluidStatus: FluidStatus[] = [ + { + fluidType: FluidType.ELECTRICITY, + status: FluidState.NOT_CONNECTED, + lastDataDate: DateTime.fromISO('2020-01-01').setZone('utc', { + keepLocalTime: true, + }), + connection: { + konnector: konnectorsData[0], + account: accountsData[0], + trigger: triggersData[0], + triggerState: triggerStateData, + shouldLaunchKonnector: false, + isUpdating: false, + konnectorConfig: { + name: 'Enedis', + oauth: true, + slug: 'enedisgrandlyon', + siteLink: 'https://mon-compte-client.enedis.fr/', + activation: 'https://mon-compte-particulier.enedis.fr/donnees/', + }, + }, + }, + ] + const result: FluidType[] = await FluidService.getOldFluidData( + mockFluidStatus + ) + expect(result).toEqual([]) + }) + + it('shoud return empty array as status is KONNECTOR_NOT_FOUND', async () => { + const mockFluidStatus: FluidStatus[] = [ + { + fluidType: FluidType.ELECTRICITY, + status: FluidState.KONNECTOR_NOT_FOUND, + lastDataDate: DateTime.fromISO('2020-01-01').setZone('utc', { + keepLocalTime: true, + }), + connection: { + konnector: konnectorsData[0], + account: accountsData[0], + trigger: triggersData[0], + triggerState: triggerStateData, + shouldLaunchKonnector: false, + isUpdating: false, + konnectorConfig: { + name: 'Enedis', + oauth: true, + slug: 'enedisgrandlyon', + siteLink: 'https://mon-compte-client.enedis.fr/', + activation: 'https://mon-compte-particulier.enedis.fr/donnees/', + }, + }, + }, + ] + const result: FluidType[] = await FluidService.getOldFluidData( + mockFluidStatus + ) + expect(result).toEqual([]) + }) + + it('shoud return empty array', async () => { + const result: FluidType[] = await FluidService.getOldFluidData([]) + expect(result).toEqual([]) + }) + }) +}) diff --git a/src/services/initialization.service.spec.ts b/src/services/initialization.service.spec.ts index 0479a05eb9db976b0c4fa4677932a59674d3d1e3..cfbf464fb5a1fc70dc371fb8fcc8ec54f20453ea 100644 --- a/src/services/initialization.service.spec.ts +++ b/src/services/initialization.service.spec.ts @@ -1,473 +1,473 @@ -import { QueryResult } from 'cozy-client' -import { DateTime } from 'luxon' -import { UserChallenge } from 'models' -import InitializationService from './initialization.service' -import mockClient from '../../test/__mocks__/client' -import { ecogesturesData } from '../../test/__mocks__/ecogesturesData.mock' -import { profileData } from '../../test/__mocks__/profile.mock' -import { fluidStatusData } from '../../test/__mocks__/fluidStatusData.mock' -import ecogestureData from 'db/ecogestureData.json' - -import { hashFile } from 'utils/hash' -import { getActualAnalysisDate } from 'utils/date' -import { FluidType } from 'enum/fluid.enum' -import { userChallengeData } from '../../test/__mocks__/userChallengeData.mock' -import { graphData } from '../../test/__mocks__/datachartData.mock' - -const mockCreateIndexKonnector = jest.fn() -jest.mock('./konnector.service', () => { - return jest.fn(() => { - return { - createIndexKonnector: mockCreateIndexKonnector, - } - }) -}) - -const mockCreateIndexAccount = jest.fn() -jest.mock('./account.service', () => { - return jest.fn(() => { - return { - createIndexAccount: mockCreateIndexAccount, - } - }) -}) - -const mockGetProfile = jest.fn() -const mockUpdateProfile = jest.fn() -jest.mock('./profile.service', () => { - return jest.fn(() => { - return { - getProfile: mockGetProfile, - updateProfile: mockUpdateProfile, - } - }) -}) - -const mockGetAllEcogestures = jest.fn() -const mockDeleteAllEcogestures = jest.fn() -jest.mock('./ecogesture.service', () => { - return jest.fn(() => { - return { - getAllEcogestures: mockGetAllEcogestures, - deleteAllEcogestures: mockDeleteAllEcogestures, - } - }) -}) - -const mockGetKonnectorAccountStatus = jest.fn() -jest.mock('./konnectorStatus.service', () => { - return jest.fn(() => { - return { - getKonnectorAccountStatus: mockGetKonnectorAccountStatus, - } - }) -}) - -const mockGetFluidStatus = jest.fn() -jest.mock('./fluid.service', () => { - return jest.fn(() => { - return { - getFluidStatus: mockGetFluidStatus, - } - }) -}) - -const mockBuildUserChallengeList = jest.fn() -const mockGetUserChallengeDataload = jest.fn() -const mockUserChallengeUpdateFlag = jest.fn() -jest.mock('./challenge.service', () => { - return jest.fn(() => { - return { - buildUserChallengeList: mockBuildUserChallengeList, - getUserChallengeDataload: mockGetUserChallengeDataload, - updateUserChallenge: mockUserChallengeUpdateFlag, - } - }) -}) - -describe('Initialization service', () => { - const initializationService = new InitializationService(mockClient) - - describe('initIndex method', () => { - it('shoud return true when all indexes created', async () => { - const mockQueryResult: QueryResult<boolean> = { - data: true, - bookmark: '', - next: false, - skip: 0, - } - mockClient.query.mockResolvedValueOnce(mockQueryResult) - mockCreateIndexKonnector.mockResolvedValueOnce(mockQueryResult) - mockCreateIndexAccount.mockResolvedValueOnce(mockQueryResult) - await expect(initializationService.initIndex()).resolves.toBe(true) - }) - - it('shoud throw error when an index is not created', async () => { - const mockQueryResult: QueryResult<boolean> = { - data: true, - bookmark: '', - next: false, - skip: 0, - } - mockClient.query.mockResolvedValueOnce(mockQueryResult) - mockCreateIndexKonnector.mockRejectedValueOnce(new Error()) - mockCreateIndexAccount.mockResolvedValueOnce(mockQueryResult) - await expect(initializationService.initIndex()).rejects.toThrow( - new Error() - ) - }) - }) - - describe('initProfile method', () => { - it('shoud return the profil when existing', async () => { - mockGetProfile.mockResolvedValueOnce(profileData) - mockUpdateProfile.mockResolvedValueOnce(profileData) - await expect(initializationService.initProfile()).resolves.toEqual( - profileData - ) - }) - - it('shoud create and return the profil when no existing', async () => { - const mockQueryResult: QueryResult<boolean> = { - data: true, - bookmark: '', - next: false, - skip: 0, - } - mockGetProfile.mockResolvedValueOnce(null) - mockClient.create.mockResolvedValueOnce(mockQueryResult) - mockUpdateProfile.mockResolvedValueOnce(profileData) - await expect(initializationService.initProfile()).resolves.toEqual( - profileData - ) - }) - - it('shoud throw error when the profile is not created', async () => { - const mockQueryResult: QueryResult<null> = { - data: null, - bookmark: '', - next: false, - skip: 0, - } - mockGetProfile.mockResolvedValueOnce(null) - mockClient.create.mockResolvedValueOnce(mockQueryResult) - await expect(initializationService.initProfile()).rejects.toThrow( - new Error('initProfile: Profile not created') - ) - }) - - it('shoud throw error when the profile could not be fetched', () => { - mockGetProfile.mockRejectedValueOnce(new Error()) - expect(initializationService.initProfile()).rejects.toEqual(new Error()) - }) - - it('shoud throw error when the profile failed to be created', () => { - mockGetProfile.mockResolvedValueOnce(null) - mockClient.create.mockRejectedValueOnce(new Error()) - expect(initializationService.initProfile()).rejects.toEqual(new Error()) - }) - }) - - describe('initEcoGesture method', () => { - it('shoud return true and profile = null when ecogestures hash is already up to date', async () => { - mockGetAllEcogestures.mockResolvedValue(ecogestureData) - await expect( - initializationService.initEcogesture(hashFile(ecogestureData)) - ).resolves.toEqual({ result: true, profile: null }) - }) - - it('shoud return true and ecogestures when ecogestures are created', async () => { - mockGetAllEcogestures - .mockResolvedValueOnce(null) - .mockResolvedValueOnce(ecogestureData) - const mockQueryResult: QueryResult<boolean> = { - data: true, - bookmark: '', - next: false, - skip: 0, - } - mockClient.create.mockResolvedValue(mockQueryResult) - const mockProfile = { - ...profileData, - ecogestureHash: hashFile(ecogestureData), - } - mockUpdateProfile.mockResolvedValueOnce(mockProfile) - await expect( - initializationService.initEcogesture(hashFile(ecogestureData)) - ).resolves.toEqual({ result: true, profile: mockProfile }) - }) - - it('shoud throw an error when ecogestures should be created and created ecogestures number does not match', async () => { - mockGetAllEcogestures - .mockResolvedValueOnce(null) - .mockResolvedValueOnce(ecogesturesData) - const mockQueryResult: QueryResult<boolean> = { - data: true, - bookmark: '', - next: false, - skip: 0, - } - mockClient.create.mockResolvedValue(mockQueryResult) - await expect( - initializationService.initEcogesture(hashFile(ecogestureData)) - ).rejects.toThrow( - new Error( - 'initEcogesture: Created ecogesture type entities does not match' - ) - ) - }) - - it('shoud throw an error when ecogestures should be created and updateProfile failed', async () => { - mockGetAllEcogestures - .mockResolvedValueOnce(null) - .mockResolvedValueOnce(ecogestureData) - mockUpdateProfile.mockResolvedValueOnce(null) - await expect( - initializationService.initEcogesture(hashFile(ecogestureData)) - ).rejects.toThrow(new Error('initEcogesture: Profile not updated')) - }) - - it('shoud throw an error when ecogestures should be created and challenge creation failed', async () => { - mockGetAllEcogestures - .mockResolvedValueOnce(null) - .mockResolvedValueOnce(ecogestureData) - mockUpdateProfile.mockRejectedValueOnce(new Error()) - await expect( - initializationService.initEcogesture(hashFile(ecogestureData)) - ).rejects.toThrow(new Error()) - }) - - it('shoud return true and profil when ecogestures are updated', async () => { - mockGetAllEcogestures - .mockResolvedValueOnce(ecogestureData) - .mockResolvedValueOnce(ecogestureData) - mockDeleteAllEcogestures.mockResolvedValue(true) - const mockQueryResult: QueryResult<boolean> = { - data: true, - bookmark: '', - next: false, - skip: 0, - } - mockClient.create.mockResolvedValue(mockQueryResult) - const mockProfile = { - ...profileData, - ecogestureHash: hashFile(ecogestureData), - } - mockUpdateProfile.mockResolvedValueOnce(mockProfile) - await expect(initializationService.initEcogesture('')).resolves.toEqual({ - result: true, - profile: mockProfile, - }) - }) - - it('shoud throw an error when ecogestures should be updated and created ecogestures number does not match', async () => { - mockGetAllEcogestures - .mockResolvedValueOnce(ecogestureData) - .mockResolvedValueOnce(ecogesturesData) - mockDeleteAllEcogestures.mockResolvedValue(true) - const mockQueryResult: QueryResult<boolean> = { - data: true, - bookmark: '', - next: false, - skip: 0, - } - mockClient.create.mockResolvedValue(mockQueryResult) - await expect(initializationService.initEcogesture('')).rejects.toThrow( - new Error( - 'initEcogesture: Created ecogesture type entities does not match' - ) - ) - }) - - it('shoud throw an error when ecogestures should be updated and updateProfile failed', async () => { - mockGetAllEcogestures - .mockResolvedValueOnce(ecogestureData) - .mockResolvedValueOnce(ecogestureData) - mockDeleteAllEcogestures.mockResolvedValue(true) - mockUpdateProfile.mockResolvedValueOnce(null) - await expect(initializationService.initEcogesture('')).rejects.toThrow( - new Error('initEcogesture: Profile not updated') - ) - }) - - it('shoud throw an error when ecogestures should be updated and ecogestures creation failed', async () => { - mockGetAllEcogestures - .mockResolvedValueOnce(ecogestureData) - .mockResolvedValueOnce(ecogestureData) - mockDeleteAllEcogestures.mockResolvedValue(true) - mockUpdateProfile.mockRejectedValueOnce(new Error()) - expect(initializationService.initEcogesture('')).rejects.toThrow( - new Error() - ) - }) - }) - - describe('initAnalysis method', () => { - it('should return true and profile when analysis is up to date', async () => { - const mockProfile = { - ...profileData, - monthlyAnalysisDate: getActualAnalysisDate(), - } - await expect( - initializationService.initAnalysis(mockProfile) - ).resolves.toEqual({ - result: true, - profile: mockProfile, - }) - }) - - it('should return true and updated profile when analysis is not up to date', async () => { - const mockProfile = { - ...profileData, - monthlyAnalysisDate: DateTime.fromISO('2000-10-02T00:00:00.000Z', { - zone: 'utc', - }), - haveSeenLastAnalysis: true, - } - const updatedProfile = { - ...profileData, - monthlyAnalysisDate: getActualAnalysisDate(), - haveSeenLastAnalysis: false, - } - mockUpdateProfile.mockResolvedValueOnce(updatedProfile) - await expect( - initializationService.initAnalysis(mockProfile) - ).resolves.toEqual({ - result: true, - profile: updatedProfile, - }) - }) - - it('should throw error when analysis is not up to date and profile is not updated', async () => { - const mockProfile = { - ...profileData, - monthlyAnalysisDate: DateTime.fromISO('2000-10-02T00:00:00.000Z', { - zone: 'utc', - }), - } - mockUpdateProfile.mockResolvedValueOnce(null) - await expect( - initializationService.initAnalysis(mockProfile) - ).rejects.toThrow(new Error('initAnalysis: Profile not updated')) - }) - - it('should throw error when analysis is not up to date and update profile failed', async () => { - const mockProfile = { - ...profileData, - monthlyAnalysisDate: DateTime.fromISO('2000-10-02T00:00:00.000Z', { - zone: 'utc', - }), - } - mockUpdateProfile.mockRejectedValueOnce(new Error()) - await expect( - initializationService.initAnalysis(mockProfile) - ).rejects.toThrow(new Error()) - }) - }) - - describe('initFluidType method', () => { - it('shoud return all fluid types', async () => { - mockGetKonnectorAccountStatus.mockResolvedValueOnce([ - FluidType.ELECTRICITY, - FluidType.WATER, - FluidType.GAS, - ]) - await expect(initializationService.initFluidTypes()).resolves.toEqual([ - FluidType.ELECTRICITY, - FluidType.WATER, - FluidType.GAS, - ]) - }) - - it('shoud throw an error when null is retrieved as fluid types', async () => { - mockGetKonnectorAccountStatus.mockResolvedValueOnce(null) - await expect(initializationService.initFluidTypes()).rejects.toThrow( - new Error('initFluidTypes: FluidTypes not found') - ) - }) - - it('shoud throw an error when it fails to retrieve the fluid types', async () => { - mockGetKonnectorAccountStatus.mockRejectedValueOnce(new Error()) - await expect(initializationService.initFluidTypes()).rejects.toThrow( - new Error() - ) - }) - }) - - describe('initFluidStatus method', () => { - it('shoud return all fluids type', async () => { - mockGetFluidStatus.mockResolvedValueOnce(fluidStatusData) - await expect(initializationService.initFluidStatus()).resolves.toEqual( - fluidStatusData - ) - }) - - it('shoud throw an error when null is retrieved as status', async () => { - mockGetFluidStatus.mockResolvedValueOnce(null) - await expect(initializationService.initFluidStatus()).rejects.toThrow( - new Error('initFluidStatus: fluidStatus not found') - ) - }) - - it('shoud throw an error when it fails to retrieve the status', async () => { - mockGetFluidStatus.mockRejectedValueOnce(new Error()) - await expect(initializationService.initFluidStatus()).rejects.toThrow( - new Error() - ) - }) - }) - - describe('initUserChallenges method', () => { - it('shoud return all userChallenges', async () => { - mockBuildUserChallengeList.mockResolvedValueOnce(userChallengeData) - await expect(initializationService.initUserChallenges()).resolves.toEqual( - userChallengeData - ) - }) - - it('shoud throw an error when null is retrieved as status', async () => { - mockBuildUserChallengeList.mockResolvedValueOnce(null) - await expect(initializationService.initUserChallenges()).rejects.toThrow( - new Error('initUserChallenges: userChallengeList not found') - ) - }) - - it('shoud throw an error when it fails to retrieve the status', async () => { - mockBuildUserChallengeList.mockRejectedValueOnce(new Error()) - await expect(initializationService.initUserChallenges()).rejects.toThrow( - new Error() - ) - }) - }) - - describe('initDuelProgress method', () => { - it('shoud return updatedUserChallenge and dataload ', async () => { - mockGetUserChallengeDataload.mockResolvedValueOnce(graphData.actualData) - - const expectedUpdatedUserChallenge: UserChallenge = { - ...userChallengeData[0], - duel: { - ...userChallengeData[0].duel, - userConsumption: 130.83585, - }, - } - mockUserChallengeUpdateFlag.mockResolvedValueOnce( - expectedUpdatedUserChallenge - ) - const expectedResult = { - updatedUserChallenge: expectedUpdatedUserChallenge, - dataloads: graphData.actualData, - } - await expect( - initializationService.initDuelProgress(userChallengeData[0]) - ).resolves.toEqual(expectedResult) - }) - - it('shoud throw an error when it fails to retrieve the status', async () => { - mockGetUserChallengeDataload.mockRejectedValueOnce(new Error()) - await expect( - initializationService.initDuelProgress(userChallengeData[0]) - ).rejects.toThrow(new Error()) - }) - }) -}) +import { QueryResult } from 'cozy-client' +import { DateTime } from 'luxon' +import { UserChallenge } from 'models' +import InitializationService from './initialization.service' +import mockClient from '../../tests/__mocks__/client' +import { ecogesturesData } from '../../tests/__mocks__/ecogesturesData.mock' +import { profileData } from '../../tests/__mocks__/profile.mock' +import { fluidStatusData } from '../../tests/__mocks__/fluidStatusData.mock' +import ecogestureData from 'db/ecogestureData.json' + +import { hashFile } from 'utils/hash' +import { getActualAnalysisDate } from 'utils/date' +import { FluidType } from 'enum/fluid.enum' +import { userChallengeData } from '../../tests/__mocks__/userChallengeData.mock' +import { graphData } from '../../tests/__mocks__/datachartData.mock' + +const mockCreateIndexKonnector = jest.fn() +jest.mock('./konnector.service', () => { + return jest.fn(() => { + return { + createIndexKonnector: mockCreateIndexKonnector, + } + }) +}) + +const mockCreateIndexAccount = jest.fn() +jest.mock('./account.service', () => { + return jest.fn(() => { + return { + createIndexAccount: mockCreateIndexAccount, + } + }) +}) + +const mockGetProfile = jest.fn() +const mockUpdateProfile = jest.fn() +jest.mock('./profile.service', () => { + return jest.fn(() => { + return { + getProfile: mockGetProfile, + updateProfile: mockUpdateProfile, + } + }) +}) + +const mockGetAllEcogestures = jest.fn() +const mockDeleteAllEcogestures = jest.fn() +jest.mock('./ecogesture.service', () => { + return jest.fn(() => { + return { + getAllEcogestures: mockGetAllEcogestures, + deleteAllEcogestures: mockDeleteAllEcogestures, + } + }) +}) + +const mockGetKonnectorAccountStatus = jest.fn() +jest.mock('./konnectorStatus.service', () => { + return jest.fn(() => { + return { + getKonnectorAccountStatus: mockGetKonnectorAccountStatus, + } + }) +}) + +const mockGetFluidStatus = jest.fn() +jest.mock('./fluid.service', () => { + return jest.fn(() => { + return { + getFluidStatus: mockGetFluidStatus, + } + }) +}) + +const mockBuildUserChallengeList = jest.fn() +const mockGetUserChallengeDataload = jest.fn() +const mockUserChallengeUpdateFlag = jest.fn() +jest.mock('./challenge.service', () => { + return jest.fn(() => { + return { + buildUserChallengeList: mockBuildUserChallengeList, + getUserChallengeDataload: mockGetUserChallengeDataload, + updateUserChallenge: mockUserChallengeUpdateFlag, + } + }) +}) + +describe('Initialization service', () => { + const initializationService = new InitializationService(mockClient) + + describe('initIndex method', () => { + it('shoud return true when all indexes created', async () => { + const mockQueryResult: QueryResult<boolean> = { + data: true, + bookmark: '', + next: false, + skip: 0, + } + mockClient.query.mockResolvedValueOnce(mockQueryResult) + mockCreateIndexKonnector.mockResolvedValueOnce(mockQueryResult) + mockCreateIndexAccount.mockResolvedValueOnce(mockQueryResult) + await expect(initializationService.initIndex()).resolves.toBe(true) + }) + + it('shoud throw error when an index is not created', async () => { + const mockQueryResult: QueryResult<boolean> = { + data: true, + bookmark: '', + next: false, + skip: 0, + } + mockClient.query.mockResolvedValueOnce(mockQueryResult) + mockCreateIndexKonnector.mockRejectedValueOnce(new Error()) + mockCreateIndexAccount.mockResolvedValueOnce(mockQueryResult) + await expect(initializationService.initIndex()).rejects.toThrow( + new Error() + ) + }) + }) + + describe('initProfile method', () => { + it('shoud return the profil when existing', async () => { + mockGetProfile.mockResolvedValueOnce(profileData) + mockUpdateProfile.mockResolvedValueOnce(profileData) + await expect(initializationService.initProfile()).resolves.toEqual( + profileData + ) + }) + + it('shoud create and return the profil when no existing', async () => { + const mockQueryResult: QueryResult<boolean> = { + data: true, + bookmark: '', + next: false, + skip: 0, + } + mockGetProfile.mockResolvedValueOnce(null) + mockClient.create.mockResolvedValueOnce(mockQueryResult) + mockUpdateProfile.mockResolvedValueOnce(profileData) + await expect(initializationService.initProfile()).resolves.toEqual( + profileData + ) + }) + + it('shoud throw error when the profile is not created', async () => { + const mockQueryResult: QueryResult<null> = { + data: null, + bookmark: '', + next: false, + skip: 0, + } + mockGetProfile.mockResolvedValueOnce(null) + mockClient.create.mockResolvedValueOnce(mockQueryResult) + await expect(initializationService.initProfile()).rejects.toThrow( + new Error('initProfile: Profile not created') + ) + }) + + it('shoud throw error when the profile could not be fetched', () => { + mockGetProfile.mockRejectedValueOnce(new Error()) + expect(initializationService.initProfile()).rejects.toEqual(new Error()) + }) + + it('shoud throw error when the profile failed to be created', () => { + mockGetProfile.mockResolvedValueOnce(null) + mockClient.create.mockRejectedValueOnce(new Error()) + expect(initializationService.initProfile()).rejects.toEqual(new Error()) + }) + }) + + describe('initEcoGesture method', () => { + it('shoud return true and profile = null when ecogestures hash is already up to date', async () => { + mockGetAllEcogestures.mockResolvedValue(ecogestureData) + await expect( + initializationService.initEcogesture(hashFile(ecogestureData)) + ).resolves.toEqual({ result: true, profile: null }) + }) + + it('shoud return true and ecogestures when ecogestures are created', async () => { + mockGetAllEcogestures + .mockResolvedValueOnce(null) + .mockResolvedValueOnce(ecogestureData) + const mockQueryResult: QueryResult<boolean> = { + data: true, + bookmark: '', + next: false, + skip: 0, + } + mockClient.create.mockResolvedValue(mockQueryResult) + const mockProfile = { + ...profileData, + ecogestureHash: hashFile(ecogestureData), + } + mockUpdateProfile.mockResolvedValueOnce(mockProfile) + await expect( + initializationService.initEcogesture(hashFile(ecogestureData)) + ).resolves.toEqual({ result: true, profile: mockProfile }) + }) + + it('shoud throw an error when ecogestures should be created and created ecogestures number does not match', async () => { + mockGetAllEcogestures + .mockResolvedValueOnce(null) + .mockResolvedValueOnce(ecogesturesData) + const mockQueryResult: QueryResult<boolean> = { + data: true, + bookmark: '', + next: false, + skip: 0, + } + mockClient.create.mockResolvedValue(mockQueryResult) + await expect( + initializationService.initEcogesture(hashFile(ecogestureData)) + ).rejects.toThrow( + new Error( + 'initEcogesture: Created ecogesture type entities does not match' + ) + ) + }) + + it('shoud throw an error when ecogestures should be created and updateProfile failed', async () => { + mockGetAllEcogestures + .mockResolvedValueOnce(null) + .mockResolvedValueOnce(ecogestureData) + mockUpdateProfile.mockResolvedValueOnce(null) + await expect( + initializationService.initEcogesture(hashFile(ecogestureData)) + ).rejects.toThrow(new Error('initEcogesture: Profile not updated')) + }) + + it('shoud throw an error when ecogestures should be created and challenge creation failed', async () => { + mockGetAllEcogestures + .mockResolvedValueOnce(null) + .mockResolvedValueOnce(ecogestureData) + mockUpdateProfile.mockRejectedValueOnce(new Error()) + await expect( + initializationService.initEcogesture(hashFile(ecogestureData)) + ).rejects.toThrow(new Error()) + }) + + it('shoud return true and profil when ecogestures are updated', async () => { + mockGetAllEcogestures + .mockResolvedValueOnce(ecogestureData) + .mockResolvedValueOnce(ecogestureData) + mockDeleteAllEcogestures.mockResolvedValue(true) + const mockQueryResult: QueryResult<boolean> = { + data: true, + bookmark: '', + next: false, + skip: 0, + } + mockClient.create.mockResolvedValue(mockQueryResult) + const mockProfile = { + ...profileData, + ecogestureHash: hashFile(ecogestureData), + } + mockUpdateProfile.mockResolvedValueOnce(mockProfile) + await expect(initializationService.initEcogesture('')).resolves.toEqual({ + result: true, + profile: mockProfile, + }) + }) + + it('shoud throw an error when ecogestures should be updated and created ecogestures number does not match', async () => { + mockGetAllEcogestures + .mockResolvedValueOnce(ecogestureData) + .mockResolvedValueOnce(ecogesturesData) + mockDeleteAllEcogestures.mockResolvedValue(true) + const mockQueryResult: QueryResult<boolean> = { + data: true, + bookmark: '', + next: false, + skip: 0, + } + mockClient.create.mockResolvedValue(mockQueryResult) + await expect(initializationService.initEcogesture('')).rejects.toThrow( + new Error( + 'initEcogesture: Created ecogesture type entities does not match' + ) + ) + }) + + it('shoud throw an error when ecogestures should be updated and updateProfile failed', async () => { + mockGetAllEcogestures + .mockResolvedValueOnce(ecogestureData) + .mockResolvedValueOnce(ecogestureData) + mockDeleteAllEcogestures.mockResolvedValue(true) + mockUpdateProfile.mockResolvedValueOnce(null) + await expect(initializationService.initEcogesture('')).rejects.toThrow( + new Error('initEcogesture: Profile not updated') + ) + }) + + it('shoud throw an error when ecogestures should be updated and ecogestures creation failed', async () => { + mockGetAllEcogestures + .mockResolvedValueOnce(ecogestureData) + .mockResolvedValueOnce(ecogestureData) + mockDeleteAllEcogestures.mockResolvedValue(true) + mockUpdateProfile.mockRejectedValueOnce(new Error()) + expect(initializationService.initEcogesture('')).rejects.toThrow( + new Error() + ) + }) + }) + + describe('initAnalysis method', () => { + it('should return true and profile when analysis is up to date', async () => { + const mockProfile = { + ...profileData, + monthlyAnalysisDate: getActualAnalysisDate(), + } + await expect( + initializationService.initAnalysis(mockProfile) + ).resolves.toEqual({ + result: true, + profile: mockProfile, + }) + }) + + it('should return true and updated profile when analysis is not up to date', async () => { + const mockProfile = { + ...profileData, + monthlyAnalysisDate: DateTime.fromISO('2000-10-02T00:00:00.000Z', { + zone: 'utc', + }), + haveSeenLastAnalysis: true, + } + const updatedProfile = { + ...profileData, + monthlyAnalysisDate: getActualAnalysisDate(), + haveSeenLastAnalysis: false, + } + mockUpdateProfile.mockResolvedValueOnce(updatedProfile) + await expect( + initializationService.initAnalysis(mockProfile) + ).resolves.toEqual({ + result: true, + profile: updatedProfile, + }) + }) + + it('should throw error when analysis is not up to date and profile is not updated', async () => { + const mockProfile = { + ...profileData, + monthlyAnalysisDate: DateTime.fromISO('2000-10-02T00:00:00.000Z', { + zone: 'utc', + }), + } + mockUpdateProfile.mockResolvedValueOnce(null) + await expect( + initializationService.initAnalysis(mockProfile) + ).rejects.toThrow(new Error('initAnalysis: Profile not updated')) + }) + + it('should throw error when analysis is not up to date and update profile failed', async () => { + const mockProfile = { + ...profileData, + monthlyAnalysisDate: DateTime.fromISO('2000-10-02T00:00:00.000Z', { + zone: 'utc', + }), + } + mockUpdateProfile.mockRejectedValueOnce(new Error()) + await expect( + initializationService.initAnalysis(mockProfile) + ).rejects.toThrow(new Error()) + }) + }) + + describe('initFluidType method', () => { + it('shoud return all fluid types', async () => { + mockGetKonnectorAccountStatus.mockResolvedValueOnce([ + FluidType.ELECTRICITY, + FluidType.WATER, + FluidType.GAS, + ]) + await expect(initializationService.initFluidTypes()).resolves.toEqual([ + FluidType.ELECTRICITY, + FluidType.WATER, + FluidType.GAS, + ]) + }) + + it('shoud throw an error when null is retrieved as fluid types', async () => { + mockGetKonnectorAccountStatus.mockResolvedValueOnce(null) + await expect(initializationService.initFluidTypes()).rejects.toThrow( + new Error('initFluidTypes: FluidTypes not found') + ) + }) + + it('shoud throw an error when it fails to retrieve the fluid types', async () => { + mockGetKonnectorAccountStatus.mockRejectedValueOnce(new Error()) + await expect(initializationService.initFluidTypes()).rejects.toThrow( + new Error() + ) + }) + }) + + describe('initFluidStatus method', () => { + it('shoud return all fluids type', async () => { + mockGetFluidStatus.mockResolvedValueOnce(fluidStatusData) + await expect(initializationService.initFluidStatus()).resolves.toEqual( + fluidStatusData + ) + }) + + it('shoud throw an error when null is retrieved as status', async () => { + mockGetFluidStatus.mockResolvedValueOnce(null) + await expect(initializationService.initFluidStatus()).rejects.toThrow( + new Error('initFluidStatus: fluidStatus not found') + ) + }) + + it('shoud throw an error when it fails to retrieve the status', async () => { + mockGetFluidStatus.mockRejectedValueOnce(new Error()) + await expect(initializationService.initFluidStatus()).rejects.toThrow( + new Error() + ) + }) + }) + + describe('initUserChallenges method', () => { + it('shoud return all userChallenges', async () => { + mockBuildUserChallengeList.mockResolvedValueOnce(userChallengeData) + await expect(initializationService.initUserChallenges()).resolves.toEqual( + userChallengeData + ) + }) + + it('shoud throw an error when null is retrieved as status', async () => { + mockBuildUserChallengeList.mockResolvedValueOnce(null) + await expect(initializationService.initUserChallenges()).rejects.toThrow( + new Error('initUserChallenges: userChallengeList not found') + ) + }) + + it('shoud throw an error when it fails to retrieve the status', async () => { + mockBuildUserChallengeList.mockRejectedValueOnce(new Error()) + await expect(initializationService.initUserChallenges()).rejects.toThrow( + new Error() + ) + }) + }) + + describe('initDuelProgress method', () => { + it('shoud return updatedUserChallenge and dataload ', async () => { + mockGetUserChallengeDataload.mockResolvedValueOnce(graphData.actualData) + + const expectedUpdatedUserChallenge: UserChallenge = { + ...userChallengeData[0], + duel: { + ...userChallengeData[0].duel, + userConsumption: 130.83585, + }, + } + mockUserChallengeUpdateFlag.mockResolvedValueOnce( + expectedUpdatedUserChallenge + ) + const expectedResult = { + updatedUserChallenge: expectedUpdatedUserChallenge, + dataloads: graphData.actualData, + } + await expect( + initializationService.initDuelProgress(userChallengeData[0]) + ).resolves.toEqual(expectedResult) + }) + + it('shoud throw an error when it fails to retrieve the status', async () => { + mockGetUserChallengeDataload.mockRejectedValueOnce(new Error()) + await expect( + initializationService.initDuelProgress(userChallengeData[0]) + ).rejects.toThrow(new Error()) + }) + }) +}) diff --git a/src/services/konnector.service.spec.ts b/src/services/konnector.service.spec.ts index 4cead0793814810c2361092ec11349887b6cba67..3067f86cc85bd5bf5e5cd735c2dc93e1cd3a7990 100644 --- a/src/services/konnector.service.spec.ts +++ b/src/services/konnector.service.spec.ts @@ -1,85 +1,85 @@ -import KonnectorService from './konnector.service' -import { Konnector } from 'models' -import mockClient from '../../test/__mocks__/client' -import { accountsData } from '../../test/__mocks__/accountsData.mock' -import { konnectorsData } from '../../test/__mocks__/konnectorsData.mock' -import { triggersData } from '../../test/__mocks__/triggersData.mock' -import { triggerStateData } from '../../test/__mocks__/triggerStateData.mock' -import { QueryResult } from 'cozy-client' - -const mockGetTrigger = jest.fn() -const mockFetchTriggerState = jest.fn() -jest.mock('./triggers.service', () => { - return jest.fn(() => { - return { - getTrigger: mockGetTrigger, - fetchTriggerState: mockFetchTriggerState, - } - }) -}) - -describe('KonnectorService service', () => { - const konnectorService = new KonnectorService(mockClient) - - describe('getKonnector method', () => { - it('shoud return konnector', async () => { - const mockQueryResult: QueryResult<Konnector[]> = { - data: [konnectorsData[0]], - bookmark: '', - next: false, - skip: 0, - } - mockClient.query.mockResolvedValueOnce(mockQueryResult) - const result = await konnectorService.getKonnector('enedisgrandlyon') - expect(result).toEqual(konnectorsData[0]) - }) - - it('shoud return null when konnector is not found', async () => { - const mockQueryResult: QueryResult<Konnector[]> = { - data: [], - bookmark: '', - next: false, - skip: 0, - } - mockClient.query.mockResolvedValueOnce(mockQueryResult) - const result = await konnectorService.getKonnector('enedisgrandlyon') - expect(result).toBeNull() - }) - }) - - describe('getKonnectorLastState method', () => { - it('shoud return the triggerState', async () => { - mockGetTrigger.mockResolvedValueOnce(triggersData[0]) - mockFetchTriggerState.mockResolvedValueOnce(triggerStateData) - const result = await konnectorService.getKonnectorLastState( - konnectorsData[0], - accountsData[0] - ) - expect(result).toEqual(triggerStateData) - }) - - it('shoud return null when trigger is not found', async () => { - mockGetTrigger.mockResolvedValueOnce(null) - mockFetchTriggerState.mockResolvedValueOnce(triggerStateData) - const result = await konnectorService.getKonnectorLastState( - konnectorsData[0], - accountsData[0] - ) - expect(result).toEqual(null) - }) - }) - - describe('createIndexKonnector method', () => { - it('shoud return the query Result', async () => { - const mockQueryResult: QueryResult<Konnector[]> = { - data: [], - bookmark: '', - next: false, - skip: 0, - } - mockClient.query.mockResolvedValueOnce(mockQueryResult) - const result = await konnectorService.createIndexKonnector() - expect(result).toEqual([]) - }) - }) -}) +import KonnectorService from './konnector.service' +import { Konnector } from 'models' +import mockClient from '../../tests/__mocks__/client' +import { accountsData } from '../../tests/__mocks__/accountsData.mock' +import { konnectorsData } from '../../tests/__mocks__/konnectorsData.mock' +import { triggersData } from '../../tests/__mocks__/triggersData.mock' +import { triggerStateData } from '../../tests/__mocks__/triggerStateData.mock' +import { QueryResult } from 'cozy-client' + +const mockGetTrigger = jest.fn() +const mockFetchTriggerState = jest.fn() +jest.mock('./triggers.service', () => { + return jest.fn(() => { + return { + getTrigger: mockGetTrigger, + fetchTriggerState: mockFetchTriggerState, + } + }) +}) + +describe('KonnectorService service', () => { + const konnectorService = new KonnectorService(mockClient) + + describe('getKonnector method', () => { + it('shoud return konnector', async () => { + const mockQueryResult: QueryResult<Konnector[]> = { + data: [konnectorsData[0]], + bookmark: '', + next: false, + skip: 0, + } + mockClient.query.mockResolvedValueOnce(mockQueryResult) + const result = await konnectorService.getKonnector('enedisgrandlyon') + expect(result).toEqual(konnectorsData[0]) + }) + + it('shoud return null when konnector is not found', async () => { + const mockQueryResult: QueryResult<Konnector[]> = { + data: [], + bookmark: '', + next: false, + skip: 0, + } + mockClient.query.mockResolvedValueOnce(mockQueryResult) + const result = await konnectorService.getKonnector('enedisgrandlyon') + expect(result).toBeNull() + }) + }) + + describe('getKonnectorLastState method', () => { + it('shoud return the triggerState', async () => { + mockGetTrigger.mockResolvedValueOnce(triggersData[0]) + mockFetchTriggerState.mockResolvedValueOnce(triggerStateData) + const result = await konnectorService.getKonnectorLastState( + konnectorsData[0], + accountsData[0] + ) + expect(result).toEqual(triggerStateData) + }) + + it('shoud return null when trigger is not found', async () => { + mockGetTrigger.mockResolvedValueOnce(null) + mockFetchTriggerState.mockResolvedValueOnce(triggerStateData) + const result = await konnectorService.getKonnectorLastState( + konnectorsData[0], + accountsData[0] + ) + expect(result).toEqual(null) + }) + }) + + describe('createIndexKonnector method', () => { + it('shoud return the query Result', async () => { + const mockQueryResult: QueryResult<Konnector[]> = { + data: [], + bookmark: '', + next: false, + skip: 0, + } + mockClient.query.mockResolvedValueOnce(mockQueryResult) + const result = await konnectorService.createIndexKonnector() + expect(result).toEqual([]) + }) + }) +}) diff --git a/src/services/konnectorStatus.service.spec.ts b/src/services/konnectorStatus.service.spec.ts index 62b694902837c7429b879529c54628e068df658b..aaf620ab3fb3be1e99f334783fc68e3869d8c233 100644 --- a/src/services/konnectorStatus.service.spec.ts +++ b/src/services/konnectorStatus.service.spec.ts @@ -1,42 +1,42 @@ -import KonnectorStatusService from './konnectorStatus.service' -import mockClient from '../../test/__mocks__/client' -import { accountsData } from '../../test/__mocks__/accountsData.mock' - -const mockGetAccountByType = jest.fn() -jest.mock('./account.service', () => { - return jest.fn(() => { - return { - getAccountByType: mockGetAccountByType, - } - }) -}) - -describe('KonnectorService service', () => { - const konnectorStatusService = new KonnectorStatusService(mockClient) - - describe('getKonnectorAccountStatus method', () => { - it('should return array with all fluid', async () => { - mockGetAccountByType - .mockResolvedValueOnce(accountsData[0]) - .mockResolvedValueOnce(accountsData[1]) - .mockResolvedValueOnce(accountsData[2]) - const result = await konnectorStatusService.getKonnectorAccountStatus() - expect(result).toEqual([0, 1, 2]) - }) - - it('should return array with elec and gaz fluid', async () => { - mockGetAccountByType - .mockResolvedValueOnce(accountsData[0]) - .mockResolvedValueOnce(null) - .mockResolvedValueOnce(accountsData[2]) - const result = await konnectorStatusService.getKonnectorAccountStatus() - expect(result).toEqual([0, 2]) - }) - - it('should return empty array', async () => { - mockGetAccountByType.mockResolvedValue(null) - const result = await konnectorStatusService.getKonnectorAccountStatus() - expect(result).toEqual([]) - }) - }) -}) +import KonnectorStatusService from './konnectorStatus.service' +import mockClient from '../../tests/__mocks__/client' +import { accountsData } from '../../tests/__mocks__/accountsData.mock' + +const mockGetAccountByType = jest.fn() +jest.mock('./account.service', () => { + return jest.fn(() => { + return { + getAccountByType: mockGetAccountByType, + } + }) +}) + +describe('KonnectorService service', () => { + const konnectorStatusService = new KonnectorStatusService(mockClient) + + describe('getKonnectorAccountStatus method', () => { + it('should return array with all fluid', async () => { + mockGetAccountByType + .mockResolvedValueOnce(accountsData[0]) + .mockResolvedValueOnce(accountsData[1]) + .mockResolvedValueOnce(accountsData[2]) + const result = await konnectorStatusService.getKonnectorAccountStatus() + expect(result).toEqual([0, 1, 2]) + }) + + it('should return array with elec and gaz fluid', async () => { + mockGetAccountByType + .mockResolvedValueOnce(accountsData[0]) + .mockResolvedValueOnce(null) + .mockResolvedValueOnce(accountsData[2]) + const result = await konnectorStatusService.getKonnectorAccountStatus() + expect(result).toEqual([0, 2]) + }) + + it('should return empty array', async () => { + mockGetAccountByType.mockResolvedValue(null) + const result = await konnectorStatusService.getKonnectorAccountStatus() + expect(result).toEqual([]) + }) + }) +}) diff --git a/src/services/mail.service.spec.ts b/src/services/mail.service.spec.ts index 448226be623b3a0bf4f4cdab14a7e4d19a1ae4f8..6dda2cd2d1d913a41862a1c43fd0a736a783ccd1 100644 --- a/src/services/mail.service.spec.ts +++ b/src/services/mail.service.spec.ts @@ -1,131 +1,131 @@ -import MailService from './mail.service' -import mockClient from '../../test/__mocks__/client' - -describe('Mail service', () => { - const mailService = new MailService() - - describe('SendMail service', () => { - it('should return void when mail is sent', async () => { - const mockMailData = { - mode: 'noreply', - subject: '[Ecolyo] - Bienvenu', - parts: [ - { - type: 'text/html', - body: '<html>Body</html>', - }, - ], - } - const result: void = await mailService.SendMail(mockClient, mockMailData) - expect(result).toEqual(undefined) - }) - - it('should throw error when failed to send mail', async () => { - let error - const mockMailData = { - mode: 'noreply', - subject: '[Ecolyo] - Bienvenu', - parts: [ - { - type: 'text/html', - body: '<html>Body</html>', - }, - ], - } - mockClient.collection('').create.mockImplementationOnce(() => { - throw new Error() - }) - try { - await mailService.SendMail(mockClient, mockMailData) - } catch (err) { - error = err - } - expect(error).toEqual(new Error('Failed to send mail')) - }) - }) - - describe('CreateBodyWelcome service', () => { - it('should return body mail with the right values when url is consumption', () => { - const result: string = mailService.CreateBodyWelcome( - 'user', - 'https://user-ecolyo.test.com/#/consumption' - ) - expect(result).toEqual(expect.stringContaining('Bonjour user')) - expect(result).toEqual( - expect.stringContaining( - '<a class="link" href="https://user-ecolyo.test.com/#/consumption">https://user-ecolyo.test.com/#/consumption</a>' - ) - ) - expect(result).toEqual( - expect.stringContaining( - '<a class="btnEcolyo" href="https://user-ecolyo.test.com/#/consumption">J\'ai compris</a>' - ) - ) - expect(result).toEqual( - expect.stringContaining( - '<a href="https://user-ecolyo.test.com/#/options" style="color: #ffffff">Unsubscribe</a>' - ) - ) - }) - it('should return body mail with the right values when url is options', () => { - const result: string = mailService.CreateBodyWelcome( - 'user', - 'https://user-ecolyo.test.com/#/options' - ) - expect(result).toEqual(expect.stringContaining('Bonjour user')) - expect(result).toEqual( - expect.stringContaining( - '<a class="link" href="https://user-ecolyo.test.com/#/options">https://user-ecolyo.test.com/#/options</a>' - ) - ) - expect(result).toEqual( - expect.stringContaining( - '<a class="btnEcolyo" href="https://user-ecolyo.test.com/#/options">J\'ai compris</a>' - ) - ) - expect(result).toEqual( - expect.stringContaining( - '<a href="https://user-ecolyo.test.com/#/options" style="color: #ffffff">Unsubscribe</a>' - ) - ) - }) - }) - - describe('CreateBodyMonthlyReport service', () => { - it('should return body mail with the right values when url is different from analysis', () => { - const result: string = mailService.CreateBodyMonthlyReport( - 'user', - 'https://user-ecolyo.test.com' - ) - expect(result).toEqual(expect.stringContaining('Bonjour user')) - expect(result).toEqual( - expect.stringContaining( - '<a class="btnEcolyo" href="https://user-ecolyo.test.com/#/analysis">' - ) - ) - expect(result).toEqual( - expect.stringContaining( - '<a href="https://user-ecolyo.test.com/#/options" style="color: #ffffff">Unsubscribe</a>' - ) - ) - }) - - it('should return body mail with the right values when url is equals to analysis', () => { - const result: string = mailService.CreateBodyMonthlyReport( - 'user', - 'https://user-ecolyo.test.com/#/analysis' - ) - expect(result).toEqual(expect.stringContaining('Bonjour user')) - expect(result).toEqual( - expect.stringContaining( - '<a class="btnEcolyo" href="https://user-ecolyo.test.com/#/analysis">' - ) - ) - expect(result).toEqual( - expect.stringContaining( - '<a href="https://user-ecolyo.test.com/#/options" style="color: #ffffff">Unsubscribe</a>' - ) - ) - }) - }) -}) +import MailService from './mail.service' +import mockClient from '../../tests/__mocks__/client' + +describe('Mail service', () => { + const mailService = new MailService() + + describe('SendMail service', () => { + it('should return void when mail is sent', async () => { + const mockMailData = { + mode: 'noreply', + subject: '[Ecolyo] - Bienvenu', + parts: [ + { + type: 'text/html', + body: '<html>Body</html>', + }, + ], + } + const result: void = await mailService.SendMail(mockClient, mockMailData) + expect(result).toEqual(undefined) + }) + + it('should throw error when failed to send mail', async () => { + let error + const mockMailData = { + mode: 'noreply', + subject: '[Ecolyo] - Bienvenu', + parts: [ + { + type: 'text/html', + body: '<html>Body</html>', + }, + ], + } + mockClient.collection('').create.mockImplementationOnce(() => { + throw new Error() + }) + try { + await mailService.SendMail(mockClient, mockMailData) + } catch (err) { + error = err + } + expect(error).toEqual(new Error('Failed to send mail')) + }) + }) + + describe('CreateBodyWelcome service', () => { + it('should return body mail with the right values when url is consumption', () => { + const result: string = mailService.CreateBodyWelcome( + 'user', + 'https://user-ecolyo.test.com/#/consumption' + ) + expect(result).toEqual(expect.stringContaining('Bonjour user')) + expect(result).toEqual( + expect.stringContaining( + '<a class="link" href="https://user-ecolyo.test.com/#/consumption">https://user-ecolyo.test.com/#/consumption</a>' + ) + ) + expect(result).toEqual( + expect.stringContaining( + '<a class="btnEcolyo" href="https://user-ecolyo.test.com/#/consumption">J\'ai compris</a>' + ) + ) + expect(result).toEqual( + expect.stringContaining( + '<a href="https://user-ecolyo.test.com/#/options" style="color: #ffffff">Unsubscribe</a>' + ) + ) + }) + it('should return body mail with the right values when url is options', () => { + const result: string = mailService.CreateBodyWelcome( + 'user', + 'https://user-ecolyo.test.com/#/options' + ) + expect(result).toEqual(expect.stringContaining('Bonjour user')) + expect(result).toEqual( + expect.stringContaining( + '<a class="link" href="https://user-ecolyo.test.com/#/options">https://user-ecolyo.test.com/#/options</a>' + ) + ) + expect(result).toEqual( + expect.stringContaining( + '<a class="btnEcolyo" href="https://user-ecolyo.test.com/#/options">J\'ai compris</a>' + ) + ) + expect(result).toEqual( + expect.stringContaining( + '<a href="https://user-ecolyo.test.com/#/options" style="color: #ffffff">Unsubscribe</a>' + ) + ) + }) + }) + + describe('CreateBodyMonthlyReport service', () => { + it('should return body mail with the right values when url is different from analysis', () => { + const result: string = mailService.CreateBodyMonthlyReport( + 'user', + 'https://user-ecolyo.test.com' + ) + expect(result).toEqual(expect.stringContaining('Bonjour user')) + expect(result).toEqual( + expect.stringContaining( + '<a class="btnEcolyo" href="https://user-ecolyo.test.com/#/analysis">' + ) + ) + expect(result).toEqual( + expect.stringContaining( + '<a href="https://user-ecolyo.test.com/#/options" style="color: #ffffff">Unsubscribe</a>' + ) + ) + }) + + it('should return body mail with the right values when url is equals to analysis', () => { + const result: string = mailService.CreateBodyMonthlyReport( + 'user', + 'https://user-ecolyo.test.com/#/analysis' + ) + expect(result).toEqual(expect.stringContaining('Bonjour user')) + expect(result).toEqual( + expect.stringContaining( + '<a class="btnEcolyo" href="https://user-ecolyo.test.com/#/analysis">' + ) + ) + expect(result).toEqual( + expect.stringContaining( + '<a href="https://user-ecolyo.test.com/#/options" style="color: #ffffff">Unsubscribe</a>' + ) + ) + }) + }) +}) diff --git a/src/services/profile.service.spec.ts b/src/services/profile.service.spec.ts index d30b6c21dd5b0a6cd1234481b19b903f9334e79e..09cf8e6c7dfa68b5dea22a298a9a932b31ae5bd1 100644 --- a/src/services/profile.service.spec.ts +++ b/src/services/profile.service.spec.ts @@ -1,129 +1,129 @@ -import ProfileService from './profile.service' -import { QueryResult } from 'cozy-client' -import { DateTime } from 'luxon' -import { Profile } from 'models' -import { profileData } from '../../test/__mocks__/profile.mock' -import mockClient from '../../test/__mocks__/client' - -describe('UserProfile service', () => { - const profileService = new ProfileService(mockClient) - - describe('getUserProfile', () => { - it('shoud return the user profile', async () => { - const mockQueryResult: QueryResult<Profile[]> = { - data: [profileData], - bookmark: '', - next: false, - skip: 0, - } - mockClient.query.mockResolvedValueOnce(mockQueryResult) - const result = await profileService.getProfile() - expect(result).toEqual(profileData) - }) - - it('shoud return the user profile from string haveSeenOldFluidModal & monthlyAnalysisDate', async () => { - const userProfile = { - ...profileData, - haveSeenOldFluidModal: '2020-11-09T11:27:30.073Z', - monthlyAnalysisDate: '2020-11-09T11:27:30.073Z', - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const mockQueryResult: QueryResult<any[]> = { - data: [userProfile], - bookmark: '', - next: false, - skip: 0, - } - mockClient.query.mockResolvedValueOnce(mockQueryResult) - const resultUserProfile = { - ...profileData, - haveSeenOldFluidModal: DateTime.fromISO('2020-11-09T11:27:30.073Z', { - zone: 'utc', - }), - monthlyAnalysisDate: DateTime.fromISO('2020-11-09T11:27:30.073Z', { - zone: 'utc', - }), - } - const result = await profileService.getProfile() - expect(result).toEqual(resultUserProfile) - }) - - it('shoud return null if no user profile found', async () => { - const mockQueryResult: QueryResult<Profile[]> = { - data: [], - bookmark: '', - next: false, - skip: 0, - } - mockClient.query.mockResolvedValueOnce(mockQueryResult) - const result = await profileService.getProfile() - expect(result).toBeNull() - }) - }) - - describe('updateUserProfile', () => { - it('shoud return an updated user profile', async () => { - const userProfile = { - ...profileData, - haveSeenOldFluidModal: '2020-11-09T11:27:30.073Z', - monthlyAnalysisDate: '2020-11-03T00:00:00.000Z', - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const mockQueryResult: QueryResult<any[]> = { - data: [userProfile], - bookmark: '', - next: false, - skip: 0, - } - mockClient.query.mockResolvedValueOnce(mockQueryResult) - const updateUserProfile = { - ...userProfile, - haveSeenLastAnalysis: false, - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const mockUpdatedQueryResult: QueryResult<any> = { - data: updateUserProfile, - bookmark: '', - next: false, - skip: 0, - } - mockClient.save.mockResolvedValueOnce(mockUpdatedQueryResult) - const resultUserProfile = { - ...profileData, - haveSeenOldFluidModal: DateTime.fromISO('2020-11-09T11:27:30.073Z', { - zone: 'utc', - }), - monthlyAnalysisDate: DateTime.fromISO('2020-11-03T00:00:00.000Z', { - zone: 'utc', - }), - haveSeenLastAnalysis: false, - } - const result = await profileService.updateProfile({ - haveSeenLastAnalysis: false, - }) - - expect(result).toEqual(resultUserProfile) - }) - - it('shoud return null if no user profile found', async () => { - const mockQueryResult: QueryResult<Profile[]> = { - data: [profileData], - bookmark: '', - next: false, - skip: 0, - } - mockClient.query.mockResolvedValueOnce(mockQueryResult) - const mockUpdatedQueryResult: QueryResult<null> = { - data: null, - bookmark: '', - next: false, - skip: 0, - } - mockClient.save.mockResolvedValueOnce(mockUpdatedQueryResult) - const result = await profileService.updateProfile({ - haveSeenLastAnalysis: false, - }) - expect(result).toBeNull() - }) - }) -}) +import ProfileService from './profile.service' +import { QueryResult } from 'cozy-client' +import { DateTime } from 'luxon' +import { Profile } from 'models' +import { profileData } from '../../tests/__mocks__/profile.mock' +import mockClient from '../../tests/__mocks__/client' + +describe('UserProfile service', () => { + const profileService = new ProfileService(mockClient) + + describe('getUserProfile', () => { + it('shoud return the user profile', async () => { + const mockQueryResult: QueryResult<Profile[]> = { + data: [profileData], + bookmark: '', + next: false, + skip: 0, + } + mockClient.query.mockResolvedValueOnce(mockQueryResult) + const result = await profileService.getProfile() + expect(result).toEqual(profileData) + }) + + it('shoud return the user profile from string haveSeenOldFluidModal & monthlyAnalysisDate', async () => { + const userProfile = { + ...profileData, + haveSeenOldFluidModal: '2020-11-09T11:27:30.073Z', + monthlyAnalysisDate: '2020-11-09T11:27:30.073Z', + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const mockQueryResult: QueryResult<any[]> = { + data: [userProfile], + bookmark: '', + next: false, + skip: 0, + } + mockClient.query.mockResolvedValueOnce(mockQueryResult) + const resultUserProfile = { + ...profileData, + haveSeenOldFluidModal: DateTime.fromISO('2020-11-09T11:27:30.073Z', { + zone: 'utc', + }), + monthlyAnalysisDate: DateTime.fromISO('2020-11-09T11:27:30.073Z', { + zone: 'utc', + }), + } + const result = await profileService.getProfile() + expect(result).toEqual(resultUserProfile) + }) + + it('shoud return null if no user profile found', async () => { + const mockQueryResult: QueryResult<Profile[]> = { + data: [], + bookmark: '', + next: false, + skip: 0, + } + mockClient.query.mockResolvedValueOnce(mockQueryResult) + const result = await profileService.getProfile() + expect(result).toBeNull() + }) + }) + + describe('updateUserProfile', () => { + it('shoud return an updated user profile', async () => { + const userProfile = { + ...profileData, + haveSeenOldFluidModal: '2020-11-09T11:27:30.073Z', + monthlyAnalysisDate: '2020-11-03T00:00:00.000Z', + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const mockQueryResult: QueryResult<any[]> = { + data: [userProfile], + bookmark: '', + next: false, + skip: 0, + } + mockClient.query.mockResolvedValueOnce(mockQueryResult) + const updateUserProfile = { + ...userProfile, + haveSeenLastAnalysis: false, + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const mockUpdatedQueryResult: QueryResult<any> = { + data: updateUserProfile, + bookmark: '', + next: false, + skip: 0, + } + mockClient.save.mockResolvedValueOnce(mockUpdatedQueryResult) + const resultUserProfile = { + ...profileData, + haveSeenOldFluidModal: DateTime.fromISO('2020-11-09T11:27:30.073Z', { + zone: 'utc', + }), + monthlyAnalysisDate: DateTime.fromISO('2020-11-03T00:00:00.000Z', { + zone: 'utc', + }), + haveSeenLastAnalysis: false, + } + const result = await profileService.updateProfile({ + haveSeenLastAnalysis: false, + }) + + expect(result).toEqual(resultUserProfile) + }) + + it('shoud return null if no user profile found', async () => { + const mockQueryResult: QueryResult<Profile[]> = { + data: [profileData], + bookmark: '', + next: false, + skip: 0, + } + mockClient.query.mockResolvedValueOnce(mockQueryResult) + const mockUpdatedQueryResult: QueryResult<null> = { + data: null, + bookmark: '', + next: false, + skip: 0, + } + mockClient.save.mockResolvedValueOnce(mockUpdatedQueryResult) + const result = await profileService.updateProfile({ + haveSeenLastAnalysis: false, + }) + expect(result).toBeNull() + }) + }) +}) diff --git a/src/services/profileType.service.spec.ts b/src/services/profileType.service.spec.ts index 42d12c75e34b3db79fbd85c0ddd17eff6357106f..54fb34f5521894613921d29cdd998e52b1a2c803 100644 --- a/src/services/profileType.service.spec.ts +++ b/src/services/profileType.service.spec.ts @@ -1,409 +1,409 @@ -import { - Floor, - HotWaterEquipment, - HousingType, - IndividualInsulationWork, - IndividualOrCollective, - ProfileTypeStepForm, - ThreeChoicesAnswer, -} from 'enum/profileType.enum' -import { ProfileType } from 'models/profileType.model' -import { - mockCorrectedConsumption, - mockEstimatedConsumption, - mockMonthColdWaterConsumption, - mockMonthConsumption, - mockMonthConsumption1, - mockMonthConsumption2, - mockMonthCookingConsumption, - mockMonthElectricSpecificConsumption, - mockMonthEcsConsumption1Solar, - mockMonthEcsConsumptionOther, - mockMonthEcsConsumptionThermo, - mockProfileType, - mockProfileType1, - mockProfileType2, - mockTestProfile1, - mockTestProfile2, - mockTestProfile3, - mockwaterRawNeeds, - mockWaterSpreadNeeds, - mockMonthlyForecastJanuaryTestProfile1, - mockMonthlyForecastJanuaryTestProfile2, - mockMonthlyForecastJanuaryTestProfile3, - mockProfileTypeAnswers, - mockMonthlyForecastJanuaryTest1WithFullArrays, -} from '../../test/__mocks__/profileType.mock' -import ProfileTypeService from './profileType.service' -const wrongNumber = 99999 -describe('ProfileType service', () => { - const profileTypeService = new ProfileTypeService(mockProfileType) - - describe('calculateWarmingEstimatedConsumption', () => { - it('shoud calculate the Warming Estimated Consumption', () => { - const estimatedConsumption = profileTypeService.calculateWarmingEstimatedConsumption() - expect(estimatedConsumption).toEqual(mockEstimatedConsumption) - }) - - it('shoud calculate the Warming Corrected Consumption', () => { - const correctedConsumption = profileTypeService.calculateWarmingCorrectedConsumption( - mockEstimatedConsumption - ) - expect(correctedConsumption).toEqual(mockCorrectedConsumption) - }) - it('shoud calculate the Warming Month Consumption', () => { - const monthConsumption = profileTypeService.calculateWarmingMonthConsumption( - mockCorrectedConsumption, - 3 - ) - expect(monthConsumption).toEqual(mockMonthConsumption) - }) - it('shoud get the heating consumption', () => { - const monthConsumption = profileTypeService.getMonthHeating(3) - expect(monthConsumption).toEqual(mockMonthConsumption) - }) - }) - describe('shoud get the heating consumption for a flat with collective heating', () => { - const _profileTypeService = new ProfileTypeService(mockProfileType1) - it('shoud get the heating consumption', () => { - const monthConsumption = _profileTypeService.getMonthHeating(2) - expect(monthConsumption).toEqual(mockMonthConsumption1) - }) - }) - describe('shoud get the heating consumption for a house with individual heating, facilities, installation and individual work', () => { - const _profileTypeService = new ProfileTypeService(mockProfileType2) - it('shoud get the heating consumption', () => { - const monthConsumption = _profileTypeService.getMonthHeating(1) - expect(monthConsumption).toEqual(mockMonthConsumption2) - }) - }) - describe('calculateMonthWaterRawNeeds', () => { - it('shoud calculate the water raw needs consumption by month', () => { - const waterRawNeeds = profileTypeService.calculateMonthWaterRawNeeds( - mockProfileType, - 1 - ) - expect(waterRawNeeds).toEqual(mockwaterRawNeeds) - }) - - it('shoud calculate the water spread needs Consumption', () => { - const waterSpreadNeeds = profileTypeService.calculateSpreadNeeds( - mockProfileType, - 1 - ) - expect(waterSpreadNeeds).toEqual(mockWaterSpreadNeeds) - }) - it('shoud calculate the total ecs consumption by month if profileType.hotWaterEquipment === "solar"', () => { - const monthEcsConsumption = profileTypeService.calculateTotalConsumption( - mockWaterSpreadNeeds, - mockProfileType1, - 1 - ) - expect(monthEcsConsumption).toEqual(mockMonthEcsConsumption1Solar) - }) - it('shoud calculate the total ecs consumption by month if profileType.hotWaterEquipment === "other"', () => { - const mockProfileTypeWithOther = { ...mockProfileType } - mockProfileTypeWithOther.hotWaterEquipment = HotWaterEquipment.OTHER - const monthEcsConsumption = profileTypeService.calculateTotalConsumption( - mockWaterSpreadNeeds, - mockProfileTypeWithOther, - 1 - ) - expect(monthEcsConsumption).toEqual(mockMonthEcsConsumptionOther) - }) - it('shoud get the ECS consumption if profileType.hotWaterEquipment === "thermodynamic"', () => { - const mockProfileTypeWithOther = { ...mockProfileType } - mockProfileTypeWithOther.hotWaterEquipment = - HotWaterEquipment.THERMODYNAMIC - const monthConsumption = profileTypeService.getMonthEcs(1) - expect(monthConsumption).toEqual(mockMonthEcsConsumptionThermo) - }) - - describe('shoud get the month cooking consumption', () => { - it('shoud get the month cooking consumption', () => { - const _profileTypeService = new ProfileTypeService(mockProfileType) - - const monthCookingConsumption = _profileTypeService.getMonthCookingConsumption( - 1 - ) - expect(monthCookingConsumption).toEqual(mockMonthCookingConsumption) - }) - }) - describe('shoud get the month electric specific consumption', () => { - it('shoud get the electric specific consumption', () => { - const _profileTypeService = new ProfileTypeService(mockProfileType) - - const monthElectricSpecificConsumption = _profileTypeService.getMonthElectricSpecificConsumption( - 1 - ) - expect(monthElectricSpecificConsumption).toEqual( - mockMonthElectricSpecificConsumption - ) - }) - }) - describe('shoud get the month cold water consumption', () => { - it('shoud get the cold water consumption', () => { - const _profileTypeService = new ProfileTypeService(mockProfileType) - const monthColdWaterConsumption = _profileTypeService.getMonthColdWaterConsumption( - 1 - ) - expect(monthColdWaterConsumption).toEqual(mockMonthColdWaterConsumption) - }) - }) - }) - describe('shoud get the monthly Forecast', () => { - // For month of january - const profileTypeService1 = new ProfileTypeService(mockTestProfile1) - it('shoud get the monthly forecast for test profile 1', () => { - const monthlyForecast = profileTypeService1.getMonthlyForecast(1) - expect(monthlyForecast).toEqual(mockMonthlyForecastJanuaryTestProfile1) - }) - const profileTypeService2 = new ProfileTypeService(mockTestProfile2) - it('shoud get the monthly forecast for test profile 2', () => { - const monthlyForecast = profileTypeService2.getMonthlyForecast(1) - expect(monthlyForecast).toEqual(mockMonthlyForecastJanuaryTestProfile2) - }) - const profileTypeService3 = new ProfileTypeService(mockTestProfile3) - it('shoud get the monthly forecast for test profile 3', () => { - const monthlyForecast = profileTypeService3.getMonthlyForecast(1) - expect(monthlyForecast).toEqual(mockMonthlyForecastJanuaryTestProfile3) - }) - it('shoud get the monthly forecast for test profile 1 with wall and roof and window insulation', () => { - const mockProfileWithThreeInsulation: ProfileType = { - ...mockTestProfile1, - individualInsulationWork: [ - IndividualInsulationWork.ROOF_INSULATION, - IndividualInsulationWork.WALL_INSULATION, - IndividualInsulationWork.WINDOW_REPLACEMENT, - ], - hasInstalledVentilation: ThreeChoicesAnswer.YES, - hasReplacedHeater: ThreeChoicesAnswer.YES, - } - const _profileTypeService = new ProfileTypeService( - mockProfileWithThreeInsulation - ) - const monthlyForecast = _profileTypeService.getMonthlyForecast(1) - expect(monthlyForecast).toEqual( - mockMonthlyForecastJanuaryTest1WithFullArrays - ) - }) - }) - describe('getNextFormStep', () => { - it('shoud get the next step in function of the current step', () => { - let nextStep = profileTypeService.getNextFormStep( - ProfileTypeStepForm.HOUSING_TYPE - ) - expect(nextStep).toEqual(ProfileTypeStepForm.AREA) - nextStep = profileTypeService.getNextFormStep(ProfileTypeStepForm.AREA) - expect(nextStep).toEqual(ProfileTypeStepForm.OCCUPANTS_NUMBER) - - nextStep = profileTypeService.getNextFormStep( - ProfileTypeStepForm.OCCUPANTS_NUMBER - ) - expect(nextStep).toEqual(ProfileTypeStepForm.CONSTRUCTION_YEAR) - nextStep = profileTypeService.getNextFormStep( - ProfileTypeStepForm.CONSTRUCTION_YEAR - ) - expect(nextStep).toEqual(ProfileTypeStepForm.OUTSIDE_FACING_WALLS) - nextStep = profileTypeService.getNextFormStep( - ProfileTypeStepForm.OUTSIDE_FACING_WALLS - ) - expect(nextStep).toEqual(ProfileTypeStepForm.FLOOR) - nextStep = profileTypeService.getNextFormStep(ProfileTypeStepForm.FLOOR) - expect(nextStep).toEqual(ProfileTypeStepForm.HEATING) - nextStep = profileTypeService.getNextFormStep(ProfileTypeStepForm.HEATING) - expect(nextStep).toEqual(ProfileTypeStepForm.WARMING_FLUID) - nextStep = profileTypeService.getNextFormStep( - ProfileTypeStepForm.WARMING_FLUID - ) - expect(nextStep).toEqual(ProfileTypeStepForm.VENTILATION) - nextStep = profileTypeService.getNextFormStep( - ProfileTypeStepForm.VENTILATION - ) - expect(nextStep).toEqual(ProfileTypeStepForm.HEATER_REPLACEMENT) - nextStep = profileTypeService.getNextFormStep( - ProfileTypeStepForm.HEATER_REPLACEMENT - ) - expect(nextStep).toEqual(ProfileTypeStepForm.COLD_WATER) - nextStep = profileTypeService.getNextFormStep( - ProfileTypeStepForm.COLD_WATER - ) - expect(nextStep).toEqual(ProfileTypeStepForm.HOT_WATER) - nextStep = profileTypeService.getNextFormStep( - ProfileTypeStepForm.HOT_WATER - ) - expect(nextStep).toEqual(ProfileTypeStepForm.HOT_WATER_FLUID) - nextStep = profileTypeService.getNextFormStep( - ProfileTypeStepForm.HOT_WATER_FLUID - ) - expect(nextStep).toEqual(ProfileTypeStepForm.HOT_WATER_EQUIPMENT) - nextStep = profileTypeService.getNextFormStep( - ProfileTypeStepForm.HOT_WATER_EQUIPMENT - ) - expect(nextStep).toEqual(ProfileTypeStepForm.COOKING_FLUID) - nextStep = profileTypeService.getNextFormStep( - ProfileTypeStepForm.COOKING_FLUID - ) - expect(nextStep).toEqual(ProfileTypeStepForm.END) - nextStep = profileTypeService.getNextFormStep(wrongNumber) - expect(nextStep).toEqual(ProfileTypeStepForm.HOUSING_TYPE) - }) - }) - describe('getPreviousFormStep', () => { - it('shoud get the previus step in function of the current step', () => { - let previousStep = profileTypeService.getPreviousFormStep( - ProfileTypeStepForm.AREA - ) - expect(previousStep).toEqual(ProfileTypeStepForm.HOUSING_TYPE) - previousStep = profileTypeService.getPreviousFormStep( - ProfileTypeStepForm.OCCUPANTS_NUMBER - ) - expect(previousStep).toEqual(ProfileTypeStepForm.AREA) - previousStep = profileTypeService.getPreviousFormStep( - ProfileTypeStepForm.CONSTRUCTION_YEAR - ) - expect(previousStep).toEqual(ProfileTypeStepForm.OCCUPANTS_NUMBER) - previousStep = profileTypeService.getPreviousFormStep( - ProfileTypeStepForm.OUTSIDE_FACING_WALLS - ) - expect(previousStep).toEqual(ProfileTypeStepForm.CONSTRUCTION_YEAR) - previousStep = profileTypeService.getPreviousFormStep( - ProfileTypeStepForm.FLOOR - ) - expect(previousStep).toEqual(ProfileTypeStepForm.OUTSIDE_FACING_WALLS) - previousStep = profileTypeService.getPreviousFormStep( - ProfileTypeStepForm.HEATING - ) - expect(previousStep).toEqual(ProfileTypeStepForm.FLOOR) - previousStep = profileTypeService.getPreviousFormStep( - ProfileTypeStepForm.WARMING_FLUID - ) - expect(previousStep).toEqual(ProfileTypeStepForm.HEATING) - previousStep = profileTypeService.getPreviousFormStep( - ProfileTypeStepForm.INDIVIDUAL_INSULATION_WORK - ) - expect(previousStep).toEqual(ProfileTypeStepForm.WARMING_FLUID) - previousStep = profileTypeService.getPreviousFormStep( - ProfileTypeStepForm.VENTILATION - ) - expect(previousStep).toEqual(ProfileTypeStepForm.WARMING_FLUID) - previousStep = profileTypeService.getPreviousFormStep( - ProfileTypeStepForm.HEATER_REPLACEMENT - ) - expect(previousStep).toEqual(ProfileTypeStepForm.VENTILATION) - previousStep = profileTypeService.getPreviousFormStep( - ProfileTypeStepForm.HOT_WATER - ) - expect(previousStep).toEqual(ProfileTypeStepForm.COLD_WATER) - previousStep = profileTypeService.getPreviousFormStep( - ProfileTypeStepForm.HOT_WATER_FLUID - ) - expect(previousStep).toEqual(ProfileTypeStepForm.HOT_WATER) - - previousStep = profileTypeService.getPreviousFormStep( - ProfileTypeStepForm.HOT_WATER_EQUIPMENT - ) - expect(previousStep).toEqual(ProfileTypeStepForm.HOT_WATER_FLUID) - previousStep = profileTypeService.getPreviousFormStep( - ProfileTypeStepForm.COOKING_FLUID - ) - expect(previousStep).toEqual(ProfileTypeStepForm.HOT_WATER_EQUIPMENT) - previousStep = profileTypeService.getPreviousFormStep(wrongNumber) - expect(previousStep).toEqual(ProfileTypeStepForm.HOUSING_TYPE) - }) - }) - describe('getAnswerForStep', () => { - it('shoud get the good answers in function of the current step', () => { - let answers = ProfileTypeService.getAnswerForStep( - ProfileTypeStepForm.HOUSING_TYPE - ) - expect(answers).toEqual(mockProfileTypeAnswers[0]) - answers = ProfileTypeService.getAnswerForStep(ProfileTypeStepForm.AREA) - expect(answers).toEqual(mockProfileTypeAnswers[1]) - answers = ProfileTypeService.getAnswerForStep( - ProfileTypeStepForm.OCCUPANTS_NUMBER - ) - expect(answers).toEqual(mockProfileTypeAnswers[2]) - answers = ProfileTypeService.getAnswerForStep( - ProfileTypeStepForm.CONSTRUCTION_YEAR - ) - expect(answers).toEqual(mockProfileTypeAnswers[3]) - answers = ProfileTypeService.getAnswerForStep( - ProfileTypeStepForm.OUTSIDE_FACING_WALLS - ) - expect(answers).toEqual(mockProfileTypeAnswers[4]) - answers = ProfileTypeService.getAnswerForStep(ProfileTypeStepForm.FLOOR) - expect(answers).toEqual(mockProfileTypeAnswers[5]) - answers = ProfileTypeService.getAnswerForStep(ProfileTypeStepForm.HEATING) - expect(answers).toEqual(mockProfileTypeAnswers[6]) - answers = ProfileTypeService.getAnswerForStep( - ProfileTypeStepForm.WARMING_FLUID - ) - expect(answers).toEqual(mockProfileTypeAnswers[7]) - answers = ProfileTypeService.getAnswerForStep( - ProfileTypeStepForm.INDIVIDUAL_INSULATION_WORK - ) - expect(answers).toEqual(mockProfileTypeAnswers[8]) - answers = ProfileTypeService.getAnswerForStep( - ProfileTypeStepForm.VENTILATION - ) - expect(answers).toEqual(mockProfileTypeAnswers[9]) - answers = ProfileTypeService.getAnswerForStep( - ProfileTypeStepForm.HEATER_REPLACEMENT - ) - expect(answers).toEqual(mockProfileTypeAnswers[10]) - answers = ProfileTypeService.getAnswerForStep( - ProfileTypeStepForm.COLD_WATER - ) - expect(answers).toEqual(mockProfileTypeAnswers[11]) - answers = ProfileTypeService.getAnswerForStep( - ProfileTypeStepForm.HOT_WATER - ) - expect(answers).toEqual(mockProfileTypeAnswers[12]) - answers = ProfileTypeService.getAnswerForStep( - ProfileTypeStepForm.HOT_WATER_FLUID - ) - expect(answers).toEqual(mockProfileTypeAnswers[13]) - answers = ProfileTypeService.getAnswerForStep( - ProfileTypeStepForm.HOT_WATER_EQUIPMENT - ) - expect(answers).toEqual(mockProfileTypeAnswers[14]) - answers = ProfileTypeService.getAnswerForStep( - ProfileTypeStepForm.COOKING_FLUID - ) - expect(answers).toEqual(mockProfileTypeAnswers[15]) - answers = ProfileTypeService.getAnswerForStep(wrongNumber) - expect(answers).toEqual(mockProfileTypeAnswers[16]) - }) - }) - describe('checkConsistency', () => { - it('shoud return consistent profile for individual house', () => { - const mockProfile = { - ...mockProfileType1, - housingType: HousingType.INDIVIDUAL_HOUSE, - } - const expectedResult = { - ...mockProfile, - floor: Floor.NOT_APPLICABLE, - heating: IndividualOrCollective.INDIVIDUAL, - coldWater: IndividualOrCollective.INDIVIDUAL, - hotWater: IndividualOrCollective.INDIVIDUAL, - } - const result = ProfileTypeService.checkConsistency(mockProfile) - expect(result).toEqual(expectedResult) - }) - it('shoud return consistent profile for appartment', () => { - const mockProfile = mockProfileType1 - const expectedResult = { - ...mockProfile, - warmingFluid: null, - individualInsulationWork: [], - facilitiesInstallation: [], - hotWaterFluid: null, - hotWaterEquipment: HotWaterEquipment.OTHER, - } - const result = ProfileTypeService.checkConsistency(mockProfile) - expect(result).toEqual(expectedResult) - }) - }) -}) +import { + Floor, + HotWaterEquipment, + HousingType, + IndividualInsulationWork, + IndividualOrCollective, + ProfileTypeStepForm, + ThreeChoicesAnswer, +} from 'enum/profileType.enum' +import { ProfileType } from 'models/profileType.model' +import { + mockCorrectedConsumption, + mockEstimatedConsumption, + mockMonthColdWaterConsumption, + mockMonthConsumption, + mockMonthConsumption1, + mockMonthConsumption2, + mockMonthCookingConsumption, + mockMonthElectricSpecificConsumption, + mockMonthEcsConsumption1Solar, + mockMonthEcsConsumptionOther, + mockMonthEcsConsumptionThermo, + mockProfileType, + mockProfileType1, + mockProfileType2, + mockTestProfile1, + mockTestProfile2, + mockTestProfile3, + mockwaterRawNeeds, + mockWaterSpreadNeeds, + mockMonthlyForecastJanuaryTestProfile1, + mockMonthlyForecastJanuaryTestProfile2, + mockMonthlyForecastJanuaryTestProfile3, + mockProfileTypeAnswers, + mockMonthlyForecastJanuaryTest1WithFullArrays, +} from '../../tests/__mocks__/profileType.mock' +import ProfileTypeService from './profileType.service' +const wrongNumber = 99999 +describe('ProfileType service', () => { + const profileTypeService = new ProfileTypeService(mockProfileType) + + describe('calculateWarmingEstimatedConsumption', () => { + it('shoud calculate the Warming Estimated Consumption', () => { + const estimatedConsumption = profileTypeService.calculateWarmingEstimatedConsumption() + expect(estimatedConsumption).toEqual(mockEstimatedConsumption) + }) + + it('shoud calculate the Warming Corrected Consumption', () => { + const correctedConsumption = profileTypeService.calculateWarmingCorrectedConsumption( + mockEstimatedConsumption + ) + expect(correctedConsumption).toEqual(mockCorrectedConsumption) + }) + it('shoud calculate the Warming Month Consumption', () => { + const monthConsumption = profileTypeService.calculateWarmingMonthConsumption( + mockCorrectedConsumption, + 3 + ) + expect(monthConsumption).toEqual(mockMonthConsumption) + }) + it('shoud get the heating consumption', () => { + const monthConsumption = profileTypeService.getMonthHeating(3) + expect(monthConsumption).toEqual(mockMonthConsumption) + }) + }) + describe('shoud get the heating consumption for a flat with collective heating', () => { + const _profileTypeService = new ProfileTypeService(mockProfileType1) + it('shoud get the heating consumption', () => { + const monthConsumption = _profileTypeService.getMonthHeating(2) + expect(monthConsumption).toEqual(mockMonthConsumption1) + }) + }) + describe('shoud get the heating consumption for a house with individual heating, facilities, installation and individual work', () => { + const _profileTypeService = new ProfileTypeService(mockProfileType2) + it('shoud get the heating consumption', () => { + const monthConsumption = _profileTypeService.getMonthHeating(1) + expect(monthConsumption).toEqual(mockMonthConsumption2) + }) + }) + describe('calculateMonthWaterRawNeeds', () => { + it('shoud calculate the water raw needs consumption by month', () => { + const waterRawNeeds = profileTypeService.calculateMonthWaterRawNeeds( + mockProfileType, + 1 + ) + expect(waterRawNeeds).toEqual(mockwaterRawNeeds) + }) + + it('shoud calculate the water spread needs Consumption', () => { + const waterSpreadNeeds = profileTypeService.calculateSpreadNeeds( + mockProfileType, + 1 + ) + expect(waterSpreadNeeds).toEqual(mockWaterSpreadNeeds) + }) + it('shoud calculate the total ecs consumption by month if profileType.hotWaterEquipment === "solar"', () => { + const monthEcsConsumption = profileTypeService.calculateTotalConsumption( + mockWaterSpreadNeeds, + mockProfileType1, + 1 + ) + expect(monthEcsConsumption).toEqual(mockMonthEcsConsumption1Solar) + }) + it('shoud calculate the total ecs consumption by month if profileType.hotWaterEquipment === "other"', () => { + const mockProfileTypeWithOther = { ...mockProfileType } + mockProfileTypeWithOther.hotWaterEquipment = HotWaterEquipment.OTHER + const monthEcsConsumption = profileTypeService.calculateTotalConsumption( + mockWaterSpreadNeeds, + mockProfileTypeWithOther, + 1 + ) + expect(monthEcsConsumption).toEqual(mockMonthEcsConsumptionOther) + }) + it('shoud get the ECS consumption if profileType.hotWaterEquipment === "thermodynamic"', () => { + const mockProfileTypeWithOther = { ...mockProfileType } + mockProfileTypeWithOther.hotWaterEquipment = + HotWaterEquipment.THERMODYNAMIC + const monthConsumption = profileTypeService.getMonthEcs(1) + expect(monthConsumption).toEqual(mockMonthEcsConsumptionThermo) + }) + + describe('shoud get the month cooking consumption', () => { + it('shoud get the month cooking consumption', () => { + const _profileTypeService = new ProfileTypeService(mockProfileType) + + const monthCookingConsumption = _profileTypeService.getMonthCookingConsumption( + 1 + ) + expect(monthCookingConsumption).toEqual(mockMonthCookingConsumption) + }) + }) + describe('shoud get the month electric specific consumption', () => { + it('shoud get the electric specific consumption', () => { + const _profileTypeService = new ProfileTypeService(mockProfileType) + + const monthElectricSpecificConsumption = _profileTypeService.getMonthElectricSpecificConsumption( + 1 + ) + expect(monthElectricSpecificConsumption).toEqual( + mockMonthElectricSpecificConsumption + ) + }) + }) + describe('shoud get the month cold water consumption', () => { + it('shoud get the cold water consumption', () => { + const _profileTypeService = new ProfileTypeService(mockProfileType) + const monthColdWaterConsumption = _profileTypeService.getMonthColdWaterConsumption( + 1 + ) + expect(monthColdWaterConsumption).toEqual(mockMonthColdWaterConsumption) + }) + }) + }) + describe('shoud get the monthly Forecast', () => { + // For month of january + const profileTypeService1 = new ProfileTypeService(mockTestProfile1) + it('shoud get the monthly forecast for test profile 1', () => { + const monthlyForecast = profileTypeService1.getMonthlyForecast(1) + expect(monthlyForecast).toEqual(mockMonthlyForecastJanuaryTestProfile1) + }) + const profileTypeService2 = new ProfileTypeService(mockTestProfile2) + it('shoud get the monthly forecast for test profile 2', () => { + const monthlyForecast = profileTypeService2.getMonthlyForecast(1) + expect(monthlyForecast).toEqual(mockMonthlyForecastJanuaryTestProfile2) + }) + const profileTypeService3 = new ProfileTypeService(mockTestProfile3) + it('shoud get the monthly forecast for test profile 3', () => { + const monthlyForecast = profileTypeService3.getMonthlyForecast(1) + expect(monthlyForecast).toEqual(mockMonthlyForecastJanuaryTestProfile3) + }) + it('shoud get the monthly forecast for test profile 1 with wall and roof and window insulation', () => { + const mockProfileWithThreeInsulation: ProfileType = { + ...mockTestProfile1, + individualInsulationWork: [ + IndividualInsulationWork.ROOF_INSULATION, + IndividualInsulationWork.WALL_INSULATION, + IndividualInsulationWork.WINDOW_REPLACEMENT, + ], + hasInstalledVentilation: ThreeChoicesAnswer.YES, + hasReplacedHeater: ThreeChoicesAnswer.YES, + } + const _profileTypeService = new ProfileTypeService( + mockProfileWithThreeInsulation + ) + const monthlyForecast = _profileTypeService.getMonthlyForecast(1) + expect(monthlyForecast).toEqual( + mockMonthlyForecastJanuaryTest1WithFullArrays + ) + }) + }) + describe('getNextFormStep', () => { + it('shoud get the next step in function of the current step', () => { + let nextStep = profileTypeService.getNextFormStep( + ProfileTypeStepForm.HOUSING_TYPE + ) + expect(nextStep).toEqual(ProfileTypeStepForm.AREA) + nextStep = profileTypeService.getNextFormStep(ProfileTypeStepForm.AREA) + expect(nextStep).toEqual(ProfileTypeStepForm.OCCUPANTS_NUMBER) + + nextStep = profileTypeService.getNextFormStep( + ProfileTypeStepForm.OCCUPANTS_NUMBER + ) + expect(nextStep).toEqual(ProfileTypeStepForm.CONSTRUCTION_YEAR) + nextStep = profileTypeService.getNextFormStep( + ProfileTypeStepForm.CONSTRUCTION_YEAR + ) + expect(nextStep).toEqual(ProfileTypeStepForm.OUTSIDE_FACING_WALLS) + nextStep = profileTypeService.getNextFormStep( + ProfileTypeStepForm.OUTSIDE_FACING_WALLS + ) + expect(nextStep).toEqual(ProfileTypeStepForm.FLOOR) + nextStep = profileTypeService.getNextFormStep(ProfileTypeStepForm.FLOOR) + expect(nextStep).toEqual(ProfileTypeStepForm.HEATING) + nextStep = profileTypeService.getNextFormStep(ProfileTypeStepForm.HEATING) + expect(nextStep).toEqual(ProfileTypeStepForm.WARMING_FLUID) + nextStep = profileTypeService.getNextFormStep( + ProfileTypeStepForm.WARMING_FLUID + ) + expect(nextStep).toEqual(ProfileTypeStepForm.VENTILATION) + nextStep = profileTypeService.getNextFormStep( + ProfileTypeStepForm.VENTILATION + ) + expect(nextStep).toEqual(ProfileTypeStepForm.HEATER_REPLACEMENT) + nextStep = profileTypeService.getNextFormStep( + ProfileTypeStepForm.HEATER_REPLACEMENT + ) + expect(nextStep).toEqual(ProfileTypeStepForm.COLD_WATER) + nextStep = profileTypeService.getNextFormStep( + ProfileTypeStepForm.COLD_WATER + ) + expect(nextStep).toEqual(ProfileTypeStepForm.HOT_WATER) + nextStep = profileTypeService.getNextFormStep( + ProfileTypeStepForm.HOT_WATER + ) + expect(nextStep).toEqual(ProfileTypeStepForm.HOT_WATER_FLUID) + nextStep = profileTypeService.getNextFormStep( + ProfileTypeStepForm.HOT_WATER_FLUID + ) + expect(nextStep).toEqual(ProfileTypeStepForm.HOT_WATER_EQUIPMENT) + nextStep = profileTypeService.getNextFormStep( + ProfileTypeStepForm.HOT_WATER_EQUIPMENT + ) + expect(nextStep).toEqual(ProfileTypeStepForm.COOKING_FLUID) + nextStep = profileTypeService.getNextFormStep( + ProfileTypeStepForm.COOKING_FLUID + ) + expect(nextStep).toEqual(ProfileTypeStepForm.END) + nextStep = profileTypeService.getNextFormStep(wrongNumber) + expect(nextStep).toEqual(ProfileTypeStepForm.HOUSING_TYPE) + }) + }) + describe('getPreviousFormStep', () => { + it('shoud get the previus step in function of the current step', () => { + let previousStep = profileTypeService.getPreviousFormStep( + ProfileTypeStepForm.AREA + ) + expect(previousStep).toEqual(ProfileTypeStepForm.HOUSING_TYPE) + previousStep = profileTypeService.getPreviousFormStep( + ProfileTypeStepForm.OCCUPANTS_NUMBER + ) + expect(previousStep).toEqual(ProfileTypeStepForm.AREA) + previousStep = profileTypeService.getPreviousFormStep( + ProfileTypeStepForm.CONSTRUCTION_YEAR + ) + expect(previousStep).toEqual(ProfileTypeStepForm.OCCUPANTS_NUMBER) + previousStep = profileTypeService.getPreviousFormStep( + ProfileTypeStepForm.OUTSIDE_FACING_WALLS + ) + expect(previousStep).toEqual(ProfileTypeStepForm.CONSTRUCTION_YEAR) + previousStep = profileTypeService.getPreviousFormStep( + ProfileTypeStepForm.FLOOR + ) + expect(previousStep).toEqual(ProfileTypeStepForm.OUTSIDE_FACING_WALLS) + previousStep = profileTypeService.getPreviousFormStep( + ProfileTypeStepForm.HEATING + ) + expect(previousStep).toEqual(ProfileTypeStepForm.FLOOR) + previousStep = profileTypeService.getPreviousFormStep( + ProfileTypeStepForm.WARMING_FLUID + ) + expect(previousStep).toEqual(ProfileTypeStepForm.HEATING) + previousStep = profileTypeService.getPreviousFormStep( + ProfileTypeStepForm.INDIVIDUAL_INSULATION_WORK + ) + expect(previousStep).toEqual(ProfileTypeStepForm.WARMING_FLUID) + previousStep = profileTypeService.getPreviousFormStep( + ProfileTypeStepForm.VENTILATION + ) + expect(previousStep).toEqual(ProfileTypeStepForm.WARMING_FLUID) + previousStep = profileTypeService.getPreviousFormStep( + ProfileTypeStepForm.HEATER_REPLACEMENT + ) + expect(previousStep).toEqual(ProfileTypeStepForm.VENTILATION) + previousStep = profileTypeService.getPreviousFormStep( + ProfileTypeStepForm.HOT_WATER + ) + expect(previousStep).toEqual(ProfileTypeStepForm.COLD_WATER) + previousStep = profileTypeService.getPreviousFormStep( + ProfileTypeStepForm.HOT_WATER_FLUID + ) + expect(previousStep).toEqual(ProfileTypeStepForm.HOT_WATER) + + previousStep = profileTypeService.getPreviousFormStep( + ProfileTypeStepForm.HOT_WATER_EQUIPMENT + ) + expect(previousStep).toEqual(ProfileTypeStepForm.HOT_WATER_FLUID) + previousStep = profileTypeService.getPreviousFormStep( + ProfileTypeStepForm.COOKING_FLUID + ) + expect(previousStep).toEqual(ProfileTypeStepForm.HOT_WATER_EQUIPMENT) + previousStep = profileTypeService.getPreviousFormStep(wrongNumber) + expect(previousStep).toEqual(ProfileTypeStepForm.HOUSING_TYPE) + }) + }) + describe('getAnswerForStep', () => { + it('shoud get the good answers in function of the current step', () => { + let answers = ProfileTypeService.getAnswerForStep( + ProfileTypeStepForm.HOUSING_TYPE + ) + expect(answers).toEqual(mockProfileTypeAnswers[0]) + answers = ProfileTypeService.getAnswerForStep(ProfileTypeStepForm.AREA) + expect(answers).toEqual(mockProfileTypeAnswers[1]) + answers = ProfileTypeService.getAnswerForStep( + ProfileTypeStepForm.OCCUPANTS_NUMBER + ) + expect(answers).toEqual(mockProfileTypeAnswers[2]) + answers = ProfileTypeService.getAnswerForStep( + ProfileTypeStepForm.CONSTRUCTION_YEAR + ) + expect(answers).toEqual(mockProfileTypeAnswers[3]) + answers = ProfileTypeService.getAnswerForStep( + ProfileTypeStepForm.OUTSIDE_FACING_WALLS + ) + expect(answers).toEqual(mockProfileTypeAnswers[4]) + answers = ProfileTypeService.getAnswerForStep(ProfileTypeStepForm.FLOOR) + expect(answers).toEqual(mockProfileTypeAnswers[5]) + answers = ProfileTypeService.getAnswerForStep(ProfileTypeStepForm.HEATING) + expect(answers).toEqual(mockProfileTypeAnswers[6]) + answers = ProfileTypeService.getAnswerForStep( + ProfileTypeStepForm.WARMING_FLUID + ) + expect(answers).toEqual(mockProfileTypeAnswers[7]) + answers = ProfileTypeService.getAnswerForStep( + ProfileTypeStepForm.INDIVIDUAL_INSULATION_WORK + ) + expect(answers).toEqual(mockProfileTypeAnswers[8]) + answers = ProfileTypeService.getAnswerForStep( + ProfileTypeStepForm.VENTILATION + ) + expect(answers).toEqual(mockProfileTypeAnswers[9]) + answers = ProfileTypeService.getAnswerForStep( + ProfileTypeStepForm.HEATER_REPLACEMENT + ) + expect(answers).toEqual(mockProfileTypeAnswers[10]) + answers = ProfileTypeService.getAnswerForStep( + ProfileTypeStepForm.COLD_WATER + ) + expect(answers).toEqual(mockProfileTypeAnswers[11]) + answers = ProfileTypeService.getAnswerForStep( + ProfileTypeStepForm.HOT_WATER + ) + expect(answers).toEqual(mockProfileTypeAnswers[12]) + answers = ProfileTypeService.getAnswerForStep( + ProfileTypeStepForm.HOT_WATER_FLUID + ) + expect(answers).toEqual(mockProfileTypeAnswers[13]) + answers = ProfileTypeService.getAnswerForStep( + ProfileTypeStepForm.HOT_WATER_EQUIPMENT + ) + expect(answers).toEqual(mockProfileTypeAnswers[14]) + answers = ProfileTypeService.getAnswerForStep( + ProfileTypeStepForm.COOKING_FLUID + ) + expect(answers).toEqual(mockProfileTypeAnswers[15]) + answers = ProfileTypeService.getAnswerForStep(wrongNumber) + expect(answers).toEqual(mockProfileTypeAnswers[16]) + }) + }) + describe('checkConsistency', () => { + it('shoud return consistent profile for individual house', () => { + const mockProfile = { + ...mockProfileType1, + housingType: HousingType.INDIVIDUAL_HOUSE, + } + const expectedResult = { + ...mockProfile, + floor: Floor.NOT_APPLICABLE, + heating: IndividualOrCollective.INDIVIDUAL, + coldWater: IndividualOrCollective.INDIVIDUAL, + hotWater: IndividualOrCollective.INDIVIDUAL, + } + const result = ProfileTypeService.checkConsistency(mockProfile) + expect(result).toEqual(expectedResult) + }) + it('shoud return consistent profile for appartment', () => { + const mockProfile = mockProfileType1 + const expectedResult = { + ...mockProfile, + warmingFluid: null, + individualInsulationWork: [], + facilitiesInstallation: [], + hotWaterFluid: null, + hotWaterEquipment: HotWaterEquipment.OTHER, + } + const result = ProfileTypeService.checkConsistency(mockProfile) + expect(result).toEqual(expectedResult) + }) + }) +}) diff --git a/src/services/queryRunner.service.spec.ts b/src/services/queryRunner.service.spec.ts index 937b2398b38b4a12a27626e0649defc210edc9a4..b2d56399a6a8934b3405c5e2931c32dfcd02ac55 100644 --- a/src/services/queryRunner.service.spec.ts +++ b/src/services/queryRunner.service.spec.ts @@ -4,11 +4,11 @@ import { TimeStep } from 'enum/timeStep.enum' import { DateTime } from 'luxon' import { Dataload, DataloadEntity } from 'models' import QueryRunner from './queryRunner.service' -import mockClient from '../../test/__mocks__/client' -import { loadYearData } from '../../test/__mocks__/loadYearData.mock' -import { loadMonthData } from '../../test/__mocks__/loadMonthData.mock' -import { loadDayData } from '../../test/__mocks__/loadDayData.mock' -import { loadMinuteData } from '../../test/__mocks__/loadMinuteData.mock' +import mockClient from '../../tests/__mocks__/client' +import { loadYearData } from '../../tests/__mocks__/loadYearData.mock' +import { loadMonthData } from '../../tests/__mocks__/loadMonthData.mock' +import { loadDayData } from '../../tests/__mocks__/loadDayData.mock' +import { loadMinuteData } from '../../tests/__mocks__/loadMinuteData.mock' describe('queryRunner service', () => { const queryRunner = new QueryRunner(mockClient) diff --git a/src/services/quiz.service.spec.ts b/src/services/quiz.service.spec.ts index 470ac16ed696ea12fef11e4620f01a366c71ee94..c244d70c3d6a431ee073acb6b1ca1bc228eb98eb 100644 --- a/src/services/quiz.service.spec.ts +++ b/src/services/quiz.service.spec.ts @@ -16,8 +16,8 @@ import { UserQuizDone, UserQuizReseted, UserQuizStarted, -} from '../../test/__mocks__/quizData.mock' -import mockClient from '../../test/__mocks__/client' +} from '../../tests/__mocks__/quizData.mock' +import mockClient from '../../tests/__mocks__/client' import QuizService from './quiz.service' import { CustomQuestionType, @@ -31,7 +31,7 @@ import { fullMonthGraphData, graphData, graphMonthData, -} from '../../test/__mocks__/datachartData.mock' +} from '../../tests/__mocks__/datachartData.mock' const localSpy = jest.spyOn(DateTime, 'local') diff --git a/src/services/triggers.service.spec.ts b/src/services/triggers.service.spec.ts index 43ae414b73e9f47234ac81d8d23149fd7d6d058f..0593ce67e66b291533dd0f2f36ebbb3b99d4ad07 100644 --- a/src/services/triggers.service.spec.ts +++ b/src/services/triggers.service.spec.ts @@ -1,103 +1,103 @@ -import { QueryResult } from 'cozy-client' -import { Trigger, TriggerState } from 'models' -import mockClient from '../../test/__mocks__/client' -import TriggerService from './triggers.service' -import { accountsData } from '../../test/__mocks__/accountsData.mock' -import { konnectorsData } from '../../test/__mocks__/konnectorsData.mock' -import { triggersData } from '../../test/__mocks__/triggersData.mock' -import { triggerStateData } from '../../test/__mocks__/triggerStateData.mock' - -const mockCreateTrigger = jest.fn() -jest.mock('cozy-harvest-lib/dist/connections/triggers', () => { - return jest.fn(() => { - return { - createTrigger: mockCreateTrigger, - } - }) -}) - -describe('TriggerService service', () => { - const triggerService = new TriggerService(mockClient) - - describe('createTrigger method', () => { - it('shoud return created Trigger', async () => { - mockCreateTrigger.mockResolvedValueOnce(triggersData[0]) - const result: Trigger = await triggerService.createTrigger( - accountsData[0], - konnectorsData[0] - ) - expect(result).toEqual(triggersData[0]) - }) - }) - - describe('getTrigger method', () => { - it('shoud return Trigger', async () => { - const mockQueryResult: QueryResult<Trigger[]> = { - data: [triggersData[0]], - bookmark: '', - next: false, - skip: 0, - } - mockClient.query.mockResolvedValueOnce(mockQueryResult) - const result: Trigger | null = await triggerService.getTrigger( - accountsData[0], - konnectorsData[0] - ) - expect(result).toEqual(triggersData[0]) - }) - - it('shoud return null when no trigger found', async () => { - const mockQueryResult: QueryResult<Trigger[]> = { - data: [], - bookmark: '', - next: false, - skip: 0, - } - mockClient.query.mockResolvedValueOnce(mockQueryResult) - const result: Trigger | null = await triggerService.getTrigger( - accountsData[0], - konnectorsData[0] - ) - expect(result).toBe(null) - }) - }) - - describe('fetchTriggerState method', () => { - it('shoud return Trigger state', async () => { - const mockResult = { - data: { - attributes: { - // eslint-disable-next-line @typescript-eslint/camelcase - current_state: triggerStateData, - }, - }, - } - mockClient.getStackClient().fetchJSON.mockResolvedValueOnce(mockResult) - const result: TriggerState | null = await triggerService.fetchTriggerState( - triggersData[0] - ) - expect(result).toEqual(triggerStateData) - }) - - it('shoud return null when current_state is empty', async () => { - const mockResult = { - // eslint-disable-next-line @typescript-eslint/camelcase - data: { attributes: { current_state: null } }, - } - mockClient.getStackClient().fetchJSON.mockResolvedValueOnce(mockResult) - const result: TriggerState | null = await triggerService.fetchTriggerState( - triggersData[0] - ) - expect(result).toBe(null) - }) - - it('shoud throw an error', async () => { - mockClient.getStackClient().fetchJSON.mockRejectedValueOnce(new Error()) - try { - await triggerService.fetchTriggerState(triggersData[0]) - } catch (error) { - expect(error).toEqual(new Error('Fetch trigger state failed')) - } - }) - }) -}) +import { QueryResult } from 'cozy-client' +import { Trigger, TriggerState } from 'models' +import mockClient from '../../tests/__mocks__/client' +import TriggerService from './triggers.service' +import { accountsData } from '../../tests/__mocks__/accountsData.mock' +import { konnectorsData } from '../../tests/__mocks__/konnectorsData.mock' +import { triggersData } from '../../tests/__mocks__/triggersData.mock' +import { triggerStateData } from '../../tests/__mocks__/triggerStateData.mock' + +const mockCreateTrigger = jest.fn() +jest.mock('cozy-harvest-lib/dist/connections/triggers', () => { + return jest.fn(() => { + return { + createTrigger: mockCreateTrigger, + } + }) +}) + +describe('TriggerService service', () => { + const triggerService = new TriggerService(mockClient) + + describe('createTrigger method', () => { + it('shoud return created Trigger', async () => { + mockCreateTrigger.mockResolvedValueOnce(triggersData[0]) + const result: Trigger = await triggerService.createTrigger( + accountsData[0], + konnectorsData[0] + ) + expect(result).toEqual(triggersData[0]) + }) + }) + + describe('getTrigger method', () => { + it('shoud return Trigger', async () => { + const mockQueryResult: QueryResult<Trigger[]> = { + data: [triggersData[0]], + bookmark: '', + next: false, + skip: 0, + } + mockClient.query.mockResolvedValueOnce(mockQueryResult) + const result: Trigger | null = await triggerService.getTrigger( + accountsData[0], + konnectorsData[0] + ) + expect(result).toEqual(triggersData[0]) + }) + + it('shoud return null when no trigger found', async () => { + const mockQueryResult: QueryResult<Trigger[]> = { + data: [], + bookmark: '', + next: false, + skip: 0, + } + mockClient.query.mockResolvedValueOnce(mockQueryResult) + const result: Trigger | null = await triggerService.getTrigger( + accountsData[0], + konnectorsData[0] + ) + expect(result).toBe(null) + }) + }) + + describe('fetchTriggerState method', () => { + it('shoud return Trigger state', async () => { + const mockResult = { + data: { + attributes: { + // eslint-disable-next-line @typescript-eslint/camelcase + current_state: triggerStateData, + }, + }, + } + mockClient.getStackClient().fetchJSON.mockResolvedValueOnce(mockResult) + const result: TriggerState | null = await triggerService.fetchTriggerState( + triggersData[0] + ) + expect(result).toEqual(triggerStateData) + }) + + it('shoud return null when current_state is empty', async () => { + const mockResult = { + // eslint-disable-next-line @typescript-eslint/camelcase + data: { attributes: { current_state: null } }, + } + mockClient.getStackClient().fetchJSON.mockResolvedValueOnce(mockResult) + const result: TriggerState | null = await triggerService.fetchTriggerState( + triggersData[0] + ) + expect(result).toBe(null) + }) + + it('shoud throw an error', async () => { + mockClient.getStackClient().fetchJSON.mockRejectedValueOnce(new Error()) + try { + await triggerService.fetchTriggerState(triggersData[0]) + } catch (error) { + expect(error).toEqual(new Error('Fetch trigger state failed')) + } + }) + }) +}) diff --git a/src/store/challenge/challenge.action.spec.ts b/src/store/challenge/challenge.action.spec.ts index f470183df76eefe73b2ae749ac5125b1698a708a..3a5819e39fdb79383cdb6e58350daa85ff7b085a 100644 --- a/src/store/challenge/challenge.action.spec.ts +++ b/src/store/challenge/challenge.action.spec.ts @@ -1,51 +1,51 @@ -import { - SET_USER_CHALLENGE_LIST, - UPDATE_USER_CHALLENGE_LIST, - UNLOCK_NEXT_USER_CHALLENGE, - SET_CHALLENGE_CONSUMPTION, - setUserChallengeList, - updateUserChallengeList, - unlockNextUserChallenge, - setChallengeConsumption, -} from './challenge.actions' -import { userChallengeData } from '../../../test/__mocks__/userChallengeData.mock' - -describe('challenge actions', () => { - it('should create an action to set userChallengeList', () => { - const expectedAction = { - type: SET_USER_CHALLENGE_LIST, - payload: userChallengeData, - } - expect(setUserChallengeList(userChallengeData)).toEqual(expectedAction) - }) - - it('should create an action to update the userChallengeList', () => { - const expectedAction = { - type: UPDATE_USER_CHALLENGE_LIST, - payload: userChallengeData[0], - } - expect(updateUserChallengeList(userChallengeData[0])).toEqual( - expectedAction - ) - }) - - it('should create an action to unlock next challenge in the list', () => { - const expectedAction = { - type: UNLOCK_NEXT_USER_CHALLENGE, - payload: userChallengeData[0], - } - expect(unlockNextUserChallenge(userChallengeData[0])).toEqual( - expectedAction - ) - }) - - it('should create an action to update challenge with consumption in the list and set current data load', () => { - const expectedAction = { - type: SET_CHALLENGE_CONSUMPTION, - payload: { userChallenge: userChallengeData[0], currentDataload: [] }, - } - expect(setChallengeConsumption(userChallengeData[0], [])).toEqual( - expectedAction - ) - }) -}) +import { + SET_USER_CHALLENGE_LIST, + UPDATE_USER_CHALLENGE_LIST, + UNLOCK_NEXT_USER_CHALLENGE, + SET_CHALLENGE_CONSUMPTION, + setUserChallengeList, + updateUserChallengeList, + unlockNextUserChallenge, + setChallengeConsumption, +} from './challenge.actions' +import { userChallengeData } from '../../../tests/__mocks__/userChallengeData.mock' + +describe('challenge actions', () => { + it('should create an action to set userChallengeList', () => { + const expectedAction = { + type: SET_USER_CHALLENGE_LIST, + payload: userChallengeData, + } + expect(setUserChallengeList(userChallengeData)).toEqual(expectedAction) + }) + + it('should create an action to update the userChallengeList', () => { + const expectedAction = { + type: UPDATE_USER_CHALLENGE_LIST, + payload: userChallengeData[0], + } + expect(updateUserChallengeList(userChallengeData[0])).toEqual( + expectedAction + ) + }) + + it('should create an action to unlock next challenge in the list', () => { + const expectedAction = { + type: UNLOCK_NEXT_USER_CHALLENGE, + payload: userChallengeData[0], + } + expect(unlockNextUserChallenge(userChallengeData[0])).toEqual( + expectedAction + ) + }) + + it('should create an action to update challenge with consumption in the list and set current data load', () => { + const expectedAction = { + type: SET_CHALLENGE_CONSUMPTION, + payload: { userChallenge: userChallengeData[0], currentDataload: [] }, + } + expect(setChallengeConsumption(userChallengeData[0], [])).toEqual( + expectedAction + ) + }) +}) diff --git a/src/store/challenge/challenge.reducer.spec.ts b/src/store/challenge/challenge.reducer.spec.ts index 0e0d9260100c7989035741d39c17cbba9d0d1e76..53959e6004d6ce511875f8f14688678e4859e696 100644 --- a/src/store/challenge/challenge.reducer.spec.ts +++ b/src/store/challenge/challenge.reducer.spec.ts @@ -1,156 +1,156 @@ -import { challengeReducer } from './challenge.reducer' -import { - SET_USER_CHALLENGE_LIST, - UPDATE_USER_CHALLENGE_LIST, - UNLOCK_NEXT_USER_CHALLENGE, - SET_CHALLENGE_CONSUMPTION, -} from './challenge.actions' -import { Dataload, ChallengeState, UserChallenge } from 'models' -import { UserChallengeState } from 'enum/userChallenge.enum' -import { - userChallengeData, - userChallengeDefault, -} from '../../../test/__mocks__/userChallengeData.mock' -import { DateTime } from 'luxon' -import { mockInitialChallengeState } from '../../../test/__mocks__/store' - -describe('challenge reducer', () => { - it('should return the initial state', () => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const result = challengeReducer(undefined as any, { type: 'default' }) - expect(result).toEqual(mockInitialChallengeState) - }) - - it('should handle SET_USER_CHALLENGE_LIST with payload', () => { - const result = challengeReducer(mockInitialChallengeState, { - type: SET_USER_CHALLENGE_LIST, - payload: userChallengeData, - }) - const expectedResult: ChallengeState = { - userChallengeList: userChallengeData, - currentChallenge: userChallengeData[2], - currentDataload: [], - } - expect(result).toEqual(expectedResult) - }) - - it('should handle SET_USER_CHALLENGE_LIST without payload', () => { - const result = challengeReducer(mockInitialChallengeState, { - type: SET_USER_CHALLENGE_LIST, - }) - expect(result).toEqual(mockInitialChallengeState) - }) - - it('should handle UPDATE_USER_CHALLENGE_LIST with payload', () => { - const updatedMockInitialChallengeState = { - ...mockInitialChallengeState, - userChallengeList: userChallengeDefault, - } - const updatedUserChallenge: UserChallenge = { - ...userChallengeDefault[0], - state: UserChallengeState.ONGOING, - } - const result = challengeReducer(updatedMockInitialChallengeState, { - type: UPDATE_USER_CHALLENGE_LIST, - payload: updatedUserChallenge, - }) - const expectedResult: ChallengeState = { - userChallengeList: [ - updatedUserChallenge, - ...userChallengeDefault.slice(1), - ], - currentChallenge: updatedUserChallenge, - currentDataload: [], - } - expect(result).toEqual(expectedResult) - }) - - it('should handle UPDATE_USER_CHALLENGE_LIST without payload', () => { - const result = challengeReducer(mockInitialChallengeState, { - type: UPDATE_USER_CHALLENGE_LIST, - }) - expect(result).toEqual(mockInitialChallengeState) - }) - - it('should handle UNLOCK_NEXT_USER_CHALLENGE with payload', () => { - const updatedMockInitialChallengeState = { - ...mockInitialChallengeState, - userChallengeList: userChallengeDefault, - } - const updatedUserChallenge: UserChallenge = { - ...userChallengeDefault[0], - state: UserChallengeState.DONE, - } - const unlockedUserChallenge: UserChallenge = { - ...userChallengeDefault[1], - state: UserChallengeState.UNLOCKED, - } - const result = challengeReducer(updatedMockInitialChallengeState, { - type: UNLOCK_NEXT_USER_CHALLENGE, - payload: updatedUserChallenge, - }) - const expectedResult: ChallengeState = { - userChallengeList: [ - updatedUserChallenge, - unlockedUserChallenge, - ...userChallengeDefault.slice(2, 6), - ], - currentChallenge: null, - currentDataload: [], - } - expect(result).toEqual(expectedResult) - }) - - it('should handle UNLOCK_NEXT_USER_CHALLENGE without payload', () => { - const result = challengeReducer(mockInitialChallengeState, { - type: UNLOCK_NEXT_USER_CHALLENGE, - }) - expect(result).toEqual(mockInitialChallengeState) - }) - - it('should handle SET_CHALLENGE_CONSUMPTION with payload', () => { - const updatedMockInitialChallengeState = { - ...mockInitialChallengeState, - userChallengeList: userChallengeDefault, - } - const dataload: Dataload[] = [ - { - date: DateTime.fromISO('2020-10-01T00:00:00.000Z', { - zone: 'utc', - }), - value: 20, - valueDetail: [5.0, 10.0, 5.0], - }, - ] - const updatedUserChallenge: UserChallenge = { - ...userChallengeDefault[0], - duel: { - ...userChallengeDefault[0].duel, - userConsumption: 20, - }, - } - const expectedResult: ChallengeState = { - userChallengeList: [ - updatedUserChallenge, - ...userChallengeDefault.slice(1, 6), - ], - currentChallenge: null, - currentDataload: dataload, - } - const result = challengeReducer(updatedMockInitialChallengeState, { - type: SET_CHALLENGE_CONSUMPTION, - payload: { - userChallenge: updatedUserChallenge, - currentDataload: dataload, - }, - }) - expect(result).toEqual(expectedResult) - }) - - it('should handle SET_CHALLENGE_CONSUMPTION without payload', () => { - const result = challengeReducer(mockInitialChallengeState, { - type: SET_CHALLENGE_CONSUMPTION, - }) - expect(result).toEqual(mockInitialChallengeState) - }) -}) +import { challengeReducer } from './challenge.reducer' +import { + SET_USER_CHALLENGE_LIST, + UPDATE_USER_CHALLENGE_LIST, + UNLOCK_NEXT_USER_CHALLENGE, + SET_CHALLENGE_CONSUMPTION, +} from './challenge.actions' +import { Dataload, ChallengeState, UserChallenge } from 'models' +import { UserChallengeState } from 'enum/userChallenge.enum' +import { + userChallengeData, + userChallengeDefault, +} from '../../../tests/__mocks__/userChallengeData.mock' +import { DateTime } from 'luxon' +import { mockInitialChallengeState } from '../../../tests/__mocks__/store' + +describe('challenge reducer', () => { + it('should return the initial state', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const result = challengeReducer(undefined as any, { type: 'default' }) + expect(result).toEqual(mockInitialChallengeState) + }) + + it('should handle SET_USER_CHALLENGE_LIST with payload', () => { + const result = challengeReducer(mockInitialChallengeState, { + type: SET_USER_CHALLENGE_LIST, + payload: userChallengeData, + }) + const expectedResult: ChallengeState = { + userChallengeList: userChallengeData, + currentChallenge: userChallengeData[2], + currentDataload: [], + } + expect(result).toEqual(expectedResult) + }) + + it('should handle SET_USER_CHALLENGE_LIST without payload', () => { + const result = challengeReducer(mockInitialChallengeState, { + type: SET_USER_CHALLENGE_LIST, + }) + expect(result).toEqual(mockInitialChallengeState) + }) + + it('should handle UPDATE_USER_CHALLENGE_LIST with payload', () => { + const updatedMockInitialChallengeState = { + ...mockInitialChallengeState, + userChallengeList: userChallengeDefault, + } + const updatedUserChallenge: UserChallenge = { + ...userChallengeDefault[0], + state: UserChallengeState.ONGOING, + } + const result = challengeReducer(updatedMockInitialChallengeState, { + type: UPDATE_USER_CHALLENGE_LIST, + payload: updatedUserChallenge, + }) + const expectedResult: ChallengeState = { + userChallengeList: [ + updatedUserChallenge, + ...userChallengeDefault.slice(1), + ], + currentChallenge: updatedUserChallenge, + currentDataload: [], + } + expect(result).toEqual(expectedResult) + }) + + it('should handle UPDATE_USER_CHALLENGE_LIST without payload', () => { + const result = challengeReducer(mockInitialChallengeState, { + type: UPDATE_USER_CHALLENGE_LIST, + }) + expect(result).toEqual(mockInitialChallengeState) + }) + + it('should handle UNLOCK_NEXT_USER_CHALLENGE with payload', () => { + const updatedMockInitialChallengeState = { + ...mockInitialChallengeState, + userChallengeList: userChallengeDefault, + } + const updatedUserChallenge: UserChallenge = { + ...userChallengeDefault[0], + state: UserChallengeState.DONE, + } + const unlockedUserChallenge: UserChallenge = { + ...userChallengeDefault[1], + state: UserChallengeState.UNLOCKED, + } + const result = challengeReducer(updatedMockInitialChallengeState, { + type: UNLOCK_NEXT_USER_CHALLENGE, + payload: updatedUserChallenge, + }) + const expectedResult: ChallengeState = { + userChallengeList: [ + updatedUserChallenge, + unlockedUserChallenge, + ...userChallengeDefault.slice(2, 6), + ], + currentChallenge: null, + currentDataload: [], + } + expect(result).toEqual(expectedResult) + }) + + it('should handle UNLOCK_NEXT_USER_CHALLENGE without payload', () => { + const result = challengeReducer(mockInitialChallengeState, { + type: UNLOCK_NEXT_USER_CHALLENGE, + }) + expect(result).toEqual(mockInitialChallengeState) + }) + + it('should handle SET_CHALLENGE_CONSUMPTION with payload', () => { + const updatedMockInitialChallengeState = { + ...mockInitialChallengeState, + userChallengeList: userChallengeDefault, + } + const dataload: Dataload[] = [ + { + date: DateTime.fromISO('2020-10-01T00:00:00.000Z', { + zone: 'utc', + }), + value: 20, + valueDetail: [5.0, 10.0, 5.0], + }, + ] + const updatedUserChallenge: UserChallenge = { + ...userChallengeDefault[0], + duel: { + ...userChallengeDefault[0].duel, + userConsumption: 20, + }, + } + const expectedResult: ChallengeState = { + userChallengeList: [ + updatedUserChallenge, + ...userChallengeDefault.slice(1, 6), + ], + currentChallenge: null, + currentDataload: dataload, + } + const result = challengeReducer(updatedMockInitialChallengeState, { + type: SET_CHALLENGE_CONSUMPTION, + payload: { + userChallenge: updatedUserChallenge, + currentDataload: dataload, + }, + }) + expect(result).toEqual(expectedResult) + }) + + it('should handle SET_CHALLENGE_CONSUMPTION without payload', () => { + const result = challengeReducer(mockInitialChallengeState, { + type: SET_CHALLENGE_CONSUMPTION, + }) + expect(result).toEqual(mockInitialChallengeState) + }) +}) diff --git a/src/store/chart/chart.action.spec.ts b/src/store/chart/chart.action.spec.ts index c0607c540b9fd23c1fb10b8b997ae7fd67f141f8..5a3815c37fa93c4374de8ec5a149cbc6bca97fd4 100644 --- a/src/store/chart/chart.action.spec.ts +++ b/src/store/chart/chart.action.spec.ts @@ -1,71 +1,71 @@ -import { TimeStep } from 'enum/timeStep.enum' -import { DateTime } from 'luxon' -import { - SET_CURRENT_TIMESTEP, - SET_SELECTED_DATE, - SET_CURRENT_INDEX, - SET_CURRENT_DATACHART, - SET_LOADING, - setCurrentTimeStep, - setSelectedDate, - setCurrentIndex, - setCurrentDatachart, - setCurrentDatachartIndex, - setLoading, - SET_CURRENT_DATACHART_INDEX, -} from './chart.actions' -import { graphData } from '../../../test/__mocks__/datachartData.mock' - -describe('chart actions', () => { - it('should create an action to set selected date', () => { - const date = DateTime.local().setZone('utc', { - keepLocalTime: true, - }) - const expectedAction = { - type: SET_SELECTED_DATE, - payload: date, - } - expect(setSelectedDate(date)).toEqual(expectedAction) - }) - - it('should create an action to set time step', () => { - const timeStep = TimeStep.DAY - const expectedAction = { - type: SET_CURRENT_TIMESTEP, - payload: timeStep, - } - expect(setCurrentTimeStep(timeStep)).toEqual(expectedAction) - }) - - it('should create an action to set index', () => { - const expectedAction = { - type: SET_CURRENT_INDEX, - payload: 1, - } - expect(setCurrentIndex(1)).toEqual(expectedAction) - }) - - it('should create an action to set datachart', () => { - const expectedAction = { - type: SET_CURRENT_DATACHART, - payload: graphData, - } - expect(setCurrentDatachart(graphData)).toEqual(expectedAction) - }) - - it('should create an action to set datachart index', () => { - const expectedAction = { - type: SET_CURRENT_DATACHART_INDEX, - payload: 1, - } - expect(setCurrentDatachartIndex(1)).toEqual(expectedAction) - }) - - it('should create an action to set loading', () => { - const expectedAction = { - type: SET_LOADING, - payload: true, - } - expect(setLoading(true)).toEqual(expectedAction) - }) -}) +import { TimeStep } from 'enum/timeStep.enum' +import { DateTime } from 'luxon' +import { + SET_CURRENT_TIMESTEP, + SET_SELECTED_DATE, + SET_CURRENT_INDEX, + SET_CURRENT_DATACHART, + SET_LOADING, + setCurrentTimeStep, + setSelectedDate, + setCurrentIndex, + setCurrentDatachart, + setCurrentDatachartIndex, + setLoading, + SET_CURRENT_DATACHART_INDEX, +} from './chart.actions' +import { graphData } from '../../../tests/__mocks__/datachartData.mock' + +describe('chart actions', () => { + it('should create an action to set selected date', () => { + const date = DateTime.local().setZone('utc', { + keepLocalTime: true, + }) + const expectedAction = { + type: SET_SELECTED_DATE, + payload: date, + } + expect(setSelectedDate(date)).toEqual(expectedAction) + }) + + it('should create an action to set time step', () => { + const timeStep = TimeStep.DAY + const expectedAction = { + type: SET_CURRENT_TIMESTEP, + payload: timeStep, + } + expect(setCurrentTimeStep(timeStep)).toEqual(expectedAction) + }) + + it('should create an action to set index', () => { + const expectedAction = { + type: SET_CURRENT_INDEX, + payload: 1, + } + expect(setCurrentIndex(1)).toEqual(expectedAction) + }) + + it('should create an action to set datachart', () => { + const expectedAction = { + type: SET_CURRENT_DATACHART, + payload: graphData, + } + expect(setCurrentDatachart(graphData)).toEqual(expectedAction) + }) + + it('should create an action to set datachart index', () => { + const expectedAction = { + type: SET_CURRENT_DATACHART_INDEX, + payload: 1, + } + expect(setCurrentDatachartIndex(1)).toEqual(expectedAction) + }) + + it('should create an action to set loading', () => { + const expectedAction = { + type: SET_LOADING, + payload: true, + } + expect(setLoading(true)).toEqual(expectedAction) + }) +}) diff --git a/src/store/chart/chart.reducer.spec.ts b/src/store/chart/chart.reducer.spec.ts index a15b816d1a589c0ac521f0918065cc8e2250eccc..ff94b5340f401ba813c2cb636f177c61e352d9dd 100644 --- a/src/store/chart/chart.reducer.spec.ts +++ b/src/store/chart/chart.reducer.spec.ts @@ -1,135 +1,135 @@ -import { chartReducer } from './chart.reducer' -import { - SET_CURRENT_TIMESTEP, - SET_SELECTED_DATE, - SET_CURRENT_INDEX, - SET_CURRENT_DATACHART, - SET_CURRENT_DATACHART_INDEX, - SET_LOADING, -} from './chart.actions' -import { DateTime } from 'luxon' -import { TimeStep } from 'enum/timeStep.enum' -import { mockInitialChartState } from '../../../test/__mocks__/store' -import { graphData } from '../../../test/__mocks__/datachartData.mock' - -describe('chart reducer', () => { - it('should return the initial state', () => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const result = chartReducer(undefined as any, { type: 'default' }) - expect(result).toEqual(mockInitialChartState) - }) - - it('should handle SET_SELECTED_DATE with payload', () => { - const mockDate = DateTime.fromISO('2021-01-01T00:00:00.000Z', { - zone: 'utc', - }) - const result = chartReducer(mockInitialChartState, { - type: SET_SELECTED_DATE, - payload: mockDate, - }) - expect(result).toEqual({ - ...mockInitialChartState, - selectedDate: mockDate, - }) - }) - - it('should handle SET_SELECTED_DATE without payload', () => { - const result = chartReducer(mockInitialChartState, { - type: SET_SELECTED_DATE, - }) - expect(result).toEqual(mockInitialChartState) - }) - - it('should handle SET_CURRENT_TIMESTEP with payload', () => { - const result = chartReducer(mockInitialChartState, { - type: SET_CURRENT_TIMESTEP, - payload: TimeStep.MONTH, - }) - expect(result).toEqual({ - ...mockInitialChartState, - currentTimeStep: TimeStep.MONTH, - }) - }) - - it('should handle SET_CURRENT_TIMESTEP without payload', () => { - const result = chartReducer(mockInitialChartState, { - type: SET_CURRENT_TIMESTEP, - }) - expect(result).toEqual(mockInitialChartState) - }) - - it('should handle SET_CURRENT_INDEX with payload', () => { - const mockDate = DateTime.fromISO('2021-01-01T00:00:00.000Z', { - zone: 'utc', - }) - const result = chartReducer(mockInitialChartState, { - type: SET_CURRENT_INDEX, - payload: mockDate, - }) - expect(result).toEqual({ - ...mockInitialChartState, - currentIndex: mockDate, - }) - }) - - it('should handle SET_CURRENT_INDEX without payload', () => { - const result = chartReducer(mockInitialChartState, { - type: SET_CURRENT_INDEX, - }) - expect(result).toEqual(mockInitialChartState) - }) - - it('should handle SET_CURRENT_DATACHART with payload', () => { - const result = chartReducer(mockInitialChartState, { - type: SET_CURRENT_DATACHART, - payload: graphData, - }) - expect(result).toEqual({ - ...mockInitialChartState, - currentDatachart: graphData, - }) - }) - - it('should handle SET_CURRENT_DATACHART without payload', () => { - const result = chartReducer(mockInitialChartState, { - type: SET_CURRENT_DATACHART, - }) - expect(result).toEqual(mockInitialChartState) - }) - - it('should handle SET_CURRENT_DATACHART_INDEX with payload', () => { - const result = chartReducer(mockInitialChartState, { - type: SET_CURRENT_DATACHART_INDEX, - payload: 1, - }) - expect(result).toEqual({ - ...mockInitialChartState, - currentDatachartIndex: 1, - }) - }) - - it('should handle SET_CURRENT_DATACHART_INDEX without payload', () => { - const result = chartReducer(mockInitialChartState, { - type: SET_CURRENT_DATACHART_INDEX, - }) - expect(result).toEqual(mockInitialChartState) - }) - - it('should handle SET_LOADING with payload', () => { - const result = chartReducer(mockInitialChartState, { - type: SET_LOADING, - payload: false, - }) - expect(result).toEqual({ - ...mockInitialChartState, - loading: false, - }) - }) - - it('should handle SET_LOADING without payload', () => { - const result = chartReducer(mockInitialChartState, { - type: SET_LOADING, - }) - expect(result).toEqual(mockInitialChartState) - }) -}) +import { chartReducer } from './chart.reducer' +import { + SET_CURRENT_TIMESTEP, + SET_SELECTED_DATE, + SET_CURRENT_INDEX, + SET_CURRENT_DATACHART, + SET_CURRENT_DATACHART_INDEX, + SET_LOADING, +} from './chart.actions' +import { DateTime } from 'luxon' +import { TimeStep } from 'enum/timeStep.enum' +import { mockInitialChartState } from '../../../tests/__mocks__/store' +import { graphData } from '../../../tests/__mocks__/datachartData.mock' + +describe('chart reducer', () => { + it('should return the initial state', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const result = chartReducer(undefined as any, { type: 'default' }) + expect(result).toEqual(mockInitialChartState) + }) + + it('should handle SET_SELECTED_DATE with payload', () => { + const mockDate = DateTime.fromISO('2021-01-01T00:00:00.000Z', { + zone: 'utc', + }) + const result = chartReducer(mockInitialChartState, { + type: SET_SELECTED_DATE, + payload: mockDate, + }) + expect(result).toEqual({ + ...mockInitialChartState, + selectedDate: mockDate, + }) + }) + + it('should handle SET_SELECTED_DATE without payload', () => { + const result = chartReducer(mockInitialChartState, { + type: SET_SELECTED_DATE, + }) + expect(result).toEqual(mockInitialChartState) + }) + + it('should handle SET_CURRENT_TIMESTEP with payload', () => { + const result = chartReducer(mockInitialChartState, { + type: SET_CURRENT_TIMESTEP, + payload: TimeStep.MONTH, + }) + expect(result).toEqual({ + ...mockInitialChartState, + currentTimeStep: TimeStep.MONTH, + }) + }) + + it('should handle SET_CURRENT_TIMESTEP without payload', () => { + const result = chartReducer(mockInitialChartState, { + type: SET_CURRENT_TIMESTEP, + }) + expect(result).toEqual(mockInitialChartState) + }) + + it('should handle SET_CURRENT_INDEX with payload', () => { + const mockDate = DateTime.fromISO('2021-01-01T00:00:00.000Z', { + zone: 'utc', + }) + const result = chartReducer(mockInitialChartState, { + type: SET_CURRENT_INDEX, + payload: mockDate, + }) + expect(result).toEqual({ + ...mockInitialChartState, + currentIndex: mockDate, + }) + }) + + it('should handle SET_CURRENT_INDEX without payload', () => { + const result = chartReducer(mockInitialChartState, { + type: SET_CURRENT_INDEX, + }) + expect(result).toEqual(mockInitialChartState) + }) + + it('should handle SET_CURRENT_DATACHART with payload', () => { + const result = chartReducer(mockInitialChartState, { + type: SET_CURRENT_DATACHART, + payload: graphData, + }) + expect(result).toEqual({ + ...mockInitialChartState, + currentDatachart: graphData, + }) + }) + + it('should handle SET_CURRENT_DATACHART without payload', () => { + const result = chartReducer(mockInitialChartState, { + type: SET_CURRENT_DATACHART, + }) + expect(result).toEqual(mockInitialChartState) + }) + + it('should handle SET_CURRENT_DATACHART_INDEX with payload', () => { + const result = chartReducer(mockInitialChartState, { + type: SET_CURRENT_DATACHART_INDEX, + payload: 1, + }) + expect(result).toEqual({ + ...mockInitialChartState, + currentDatachartIndex: 1, + }) + }) + + it('should handle SET_CURRENT_DATACHART_INDEX without payload', () => { + const result = chartReducer(mockInitialChartState, { + type: SET_CURRENT_DATACHART_INDEX, + }) + expect(result).toEqual(mockInitialChartState) + }) + + it('should handle SET_LOADING with payload', () => { + const result = chartReducer(mockInitialChartState, { + type: SET_LOADING, + payload: false, + }) + expect(result).toEqual({ + ...mockInitialChartState, + loading: false, + }) + }) + + it('should handle SET_LOADING without payload', () => { + const result = chartReducer(mockInitialChartState, { + type: SET_LOADING, + }) + expect(result).toEqual(mockInitialChartState) + }) +}) diff --git a/src/store/global/global.action.spec.ts b/src/store/global/global.action.spec.ts index 5a7db613eec2681ef619976b5e3eb2f3bbf3179b..b374527590ebff484375efccd5fa59390696c19c 100644 --- a/src/store/global/global.action.spec.ts +++ b/src/store/global/global.action.spec.ts @@ -1,5 +1,5 @@ import { ScreenType } from 'enum/screen.enum' -import { mockInitialGlobalState } from '../../../test/__mocks__/store' +import { mockInitialGlobalState } from '../../../tests/__mocks__/store' import { CHANGE_SCREEN_TYPE, TOOGLE_CHALLENGE_EXPLORATION_NOTIFICATION, diff --git a/src/store/global/global.reducer.spec.ts b/src/store/global/global.reducer.spec.ts index 88790f01fc37b076a26ccc885cb41a6879ce3339..40a9bfb06d448c822c6de5e160ec7ca4309c181b 100644 --- a/src/store/global/global.reducer.spec.ts +++ b/src/store/global/global.reducer.spec.ts @@ -11,10 +11,10 @@ import { ScreenType } from 'enum/screen.enum' import { FluidStatus } from 'models' import { FluidState, FluidType } from 'enum/fluid.enum' import { DateTime } from 'luxon' -import { konnectorsData } from '../../../test/__mocks__/konnectorsData.mock' -import { accountsData } from '../../../test/__mocks__/accountsData.mock' -import { triggersData } from '../../../test/__mocks__/triggersData.mock' -import { mockInitialGlobalState } from '../../../test/__mocks__/store' +import { konnectorsData } from '../../../tests/__mocks__/konnectorsData.mock' +import { accountsData } from '../../../tests/__mocks__/accountsData.mock' +import { triggersData } from '../../../tests/__mocks__/triggersData.mock' +import { mockInitialGlobalState } from '../../../tests/__mocks__/store' const mockLastDataDates: (DateTime | null)[] = [ DateTime.local().setZone('utc', { diff --git a/src/store/modal/modal.reducer.spec.ts b/src/store/modal/modal.reducer.spec.ts index f17055cae7853dcd29f4c4e9f559c66b7929cfb3..4735069aff9a4f38dedd1229190140c2016a5ef3 100644 --- a/src/store/modal/modal.reducer.spec.ts +++ b/src/store/modal/modal.reducer.spec.ts @@ -1,29 +1,29 @@ -import { modalReducer } from './modal.reducer' -import { UPDATE_MODAL_ISFEEDBACKSOPEN } from './modal.actions' -import { mockInitialModalState } from '../../../test/__mocks__/store' - -describe('modal reducer', () => { - it('should return the initial state', () => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const result = modalReducer(undefined as any, { type: 'default' }) - expect(result).toEqual(mockInitialModalState) - }) - - it('should handle UPDATE_MODAL_ISFEEDBACKSOPEN with payload', () => { - const result = modalReducer(mockInitialModalState, { - type: UPDATE_MODAL_ISFEEDBACKSOPEN, - payload: true, - }) - expect(result).toEqual({ - ...mockInitialModalState, - isFeedbacksOpen: true, - }) - }) - - it('should handle UPDATE_MODAL_ISFEEDBACKSOPEN without payload', () => { - const result = modalReducer(mockInitialModalState, { - type: UPDATE_MODAL_ISFEEDBACKSOPEN, - }) - expect(result).toEqual(mockInitialModalState) - }) -}) +import { modalReducer } from './modal.reducer' +import { UPDATE_MODAL_ISFEEDBACKSOPEN } from './modal.actions' +import { mockInitialModalState } from '../../../tests/__mocks__/store' + +describe('modal reducer', () => { + it('should return the initial state', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const result = modalReducer(undefined as any, { type: 'default' }) + expect(result).toEqual(mockInitialModalState) + }) + + it('should handle UPDATE_MODAL_ISFEEDBACKSOPEN with payload', () => { + const result = modalReducer(mockInitialModalState, { + type: UPDATE_MODAL_ISFEEDBACKSOPEN, + payload: true, + }) + expect(result).toEqual({ + ...mockInitialModalState, + isFeedbacksOpen: true, + }) + }) + + it('should handle UPDATE_MODAL_ISFEEDBACKSOPEN without payload', () => { + const result = modalReducer(mockInitialModalState, { + type: UPDATE_MODAL_ISFEEDBACKSOPEN, + }) + expect(result).toEqual(mockInitialModalState) + }) +}) diff --git a/src/store/profile/profile.action.spec.ts b/src/store/profile/profile.action.spec.ts index 3aa86aad064190c7c747cf4fa0f85d6f615e93b4..a1b52ed7a25e5e80d231c577c4b04227f6b65237 100644 --- a/src/store/profile/profile.action.spec.ts +++ b/src/store/profile/profile.action.spec.ts @@ -1,40 +1,40 @@ -import { UPDATE_PROFILE, updateProfile } from './profile.actions' -import { profileData } from '../../../test/__mocks__/profile.mock' -import { - createMockStore, - mockInitialEcolyoState, -} from '../../../test/__mocks__/store' - -const mockUpdateProfile = jest.fn() -jest.mock('services/profile.service', () => { - return jest.fn(() => { - return { - updateProfile: mockUpdateProfile, - } - }) -}) - -describe('profile actions', () => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let store: any - beforeEach(() => { - store = createMockStore(mockInitialEcolyoState) - }) - it('should create an UPDATE_PROFILE action when profile is updated', async () => { - mockUpdateProfile.mockResolvedValueOnce(profileData) - const expectedActions = [ - { - type: UPDATE_PROFILE, - payload: profileData, - }, - ] - await store.dispatch(updateProfile(profileData)) - expect(store.getActions()).toEqual(expectedActions) - }) - - it('should not create action when profile is not updated', async () => { - mockUpdateProfile.mockResolvedValueOnce(null) - await store.dispatch(updateProfile(profileData)) - expect(store.getActions()).toEqual([]) - }) -}) +import { UPDATE_PROFILE, updateProfile } from './profile.actions' +import { profileData } from '../../../tests/__mocks__/profile.mock' +import { + createMockStore, + mockInitialEcolyoState, +} from '../../../tests/__mocks__/store' + +const mockUpdateProfile = jest.fn() +jest.mock('services/profile.service', () => { + return jest.fn(() => { + return { + updateProfile: mockUpdateProfile, + } + }) +}) + +describe('profile actions', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let store: any + beforeEach(() => { + store = createMockStore(mockInitialEcolyoState) + }) + it('should create an UPDATE_PROFILE action when profile is updated', async () => { + mockUpdateProfile.mockResolvedValueOnce(profileData) + const expectedActions = [ + { + type: UPDATE_PROFILE, + payload: profileData, + }, + ] + await store.dispatch(updateProfile(profileData)) + expect(store.getActions()).toEqual(expectedActions) + }) + + it('should not create action when profile is not updated', async () => { + mockUpdateProfile.mockResolvedValueOnce(null) + await store.dispatch(updateProfile(profileData)) + expect(store.getActions()).toEqual([]) + }) +}) diff --git a/src/store/profile/profile.reducer.spec.ts b/src/store/profile/profile.reducer.spec.ts index 96f600f90ad0aa813253dba440b3373c7eb40595..e547bfc134d758e39cf4814d5046f8e169c4dc3c 100644 --- a/src/store/profile/profile.reducer.spec.ts +++ b/src/store/profile/profile.reducer.spec.ts @@ -1,27 +1,27 @@ -import { profileReducer } from './profile.reducer' -import { UPDATE_PROFILE } from './profile.actions' -import { mockInitialProfileState } from '../../../test/__mocks__/store' -import { profileData } from '../../../test/__mocks__/profile.mock' - -describe('profile reducer', () => { - it('should return the initial state', () => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const result = profileReducer(undefined as any, { type: 'default' }) - expect(result).toEqual(mockInitialProfileState) - }) - - it('should handle UPDATE_PROFILE with payload', () => { - const result = profileReducer(mockInitialProfileState, { - type: UPDATE_PROFILE, - payload: profileData, - }) - expect(result).toEqual(profileData) - }) - - it('should handle UPDATE_PROFILE without payload', () => { - const result = profileReducer(mockInitialProfileState, { - type: UPDATE_PROFILE, - }) - expect(result).toEqual(mockInitialProfileState) - }) -}) +import { profileReducer } from './profile.reducer' +import { UPDATE_PROFILE } from './profile.actions' +import { mockInitialProfileState } from '../../../tests/__mocks__/store' +import { profileData } from '../../../tests/__mocks__/profile.mock' + +describe('profile reducer', () => { + it('should return the initial state', () => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const result = profileReducer(undefined as any, { type: 'default' }) + expect(result).toEqual(mockInitialProfileState) + }) + + it('should handle UPDATE_PROFILE with payload', () => { + const result = profileReducer(mockInitialProfileState, { + type: UPDATE_PROFILE, + payload: profileData, + }) + expect(result).toEqual(profileData) + }) + + it('should handle UPDATE_PROFILE without payload', () => { + const result = profileReducer(mockInitialProfileState, { + type: UPDATE_PROFILE, + }) + expect(result).toEqual(mockInitialProfileState) + }) +}) diff --git a/src/cozy-bar.d.ts b/src/types/cozy-bar.d.ts similarity index 96% rename from src/cozy-bar.d.ts rename to src/types/cozy-bar.d.ts index 419aba059185291edb379995941a8b3a6f309d50..706ada9899bb9771266707671abcb7891f7ca57f 100644 --- a/src/cozy-bar.d.ts +++ b/src/types/cozy-bar.d.ts @@ -1,36 +1,36 @@ -import { ReactComponentElement } from 'react' - -/* eslint-disable @typescript-eslint/no-explicit-any */ -declare module 'cozy-bar' { - type TcozyBarInitOpts = { - appName: string - appNamePrefix: string - appSlug?: string - lang: string - iconPath: string - cozyClient: Client - cozyURL?: string - ssl?: boolean - token?: string - replaceTitleOnMobile: boolean - isPublic?: boolean - onLogOut?: () => any - } - - declare global { - const cozy: { - bar: { - BarCenter: (children: ReactComponentElement) => any - BarLeft: (children: ReactComponentElement) => any - BarRight: (children: ReactComponentElement) => any - init: (opt: TcozyBarInitOpts) => any - setBarCenter: (e: string) => any - setBarLeft: (e: string) => any - setBarRight: (e: string) => any - setLocale: (e: any) => any - setTheme: (theme: string, opts?: any) => any - updateAccessToken: (e: any) => any - } - } - } -} +import { ReactComponentElement } from 'react' + +/* eslint-disable @typescript-eslint/no-explicit-any */ +declare module 'cozy-bar' { + type TcozyBarInitOpts = { + appName: string + appNamePrefix: string + appSlug?: string + lang: string + iconPath: string + cozyClient: Client + cozyURL?: string + ssl?: boolean + token?: string + replaceTitleOnMobile: boolean + isPublic?: boolean + onLogOut?: () => any + } + + declare global { + const cozy: { + bar: { + BarCenter: (children: ReactComponentElement) => any + BarLeft: (children: ReactComponentElement) => any + BarRight: (children: ReactComponentElement) => any + init: (opt: TcozyBarInitOpts) => any + setBarCenter: (e: string) => any + setBarLeft: (e: string) => any + setBarRight: (e: string) => any + setLocale: (e: any) => any + setTheme: (theme: string, opts?: any) => any + updateAccessToken: (e: any) => any + } + } + } +} diff --git a/src/cozy-client.d.ts b/src/types/cozy-client.d.ts similarity index 97% rename from src/cozy-client.d.ts rename to src/types/cozy-client.d.ts index d47de75b0c4c6c6883f44a33985a96080f61fc3f..03520bfb6b7ff8cb2337b1eb44ea9615f81d5b26 100644 --- a/src/cozy-client.d.ts +++ b/src/types/cozy-client.d.ts @@ -1,371 +1,371 @@ -import * as CozyStackClient from 'cozy-stack-client' -import { TRealtimePlugin, RealtimePlugin } from 'cozy-realtime' -import { TDoctype } from 'doctypes' -import { CozyMetadata, Relation } from 'models' - -declare module 'cozy-client' { - /** - * @typedef {object} HydratedDocument - */ - - export const CozyProvider: React.FC<{ client: Client; store?: any }> - - export function useClient(): Client - export function Q(doctype: TDoctype): QueryDefinition - - export type SortOptions = { [field: string]: 'asc' | 'desc' } - export type QueryDefinition = { - checkSortOrder(opts: { - sort: SortOptions - selector: unknown - indexedFields: unknown - }): QueryDefinition - getById(id: string): QueryDefinition - getByIds(ids: Array<string>): QueryDefinition - include(relations: Array<string>): QueryDefinition - indexFields(indexedFields: Array<string>): QueryDefinition - limitBy(limit: number): QueryDefinition - offset(skip: number): QueryDefinition - offsetBookmark(bookmark: string): QueryDefinition - offsetCursor(cursor): QueryDefinition - referencedBy(document: unknown): QueryDefinition - select(field: Array<string> | undefined): QueryDefinition - sortBy(sort: Array<SortOptions>): QueryDefinition - where(selector: MongoSelector): QueryDefinition - } - export type QueryResult<T, I = undefined> = { - bookmark: string - next: boolean - meta?: { count: number } - skip: number - data: T - included?: I - } - - export interface MongoSelector { - [field: unknown]: unknown - } - export interface AllQueryOptions { - bookmark?: string - keys?: unknown - limit?: number - skip?: number - } - export interface FindQueryOptions { - bookmark?: string - fields?: Array<string> - indexId?: string - limit?: number - skip?: number - sort?: SortOptions[] - } - interface ClientInstanceOpts { - cozyAppEditor: string - cozyAppName: string - cozyAppNamePrefix: string - cozyAppSlug: string - cozyDomain: string - cozyIconPath: string - cozyLocale: string - cozyToken: string - } - interface ClientToJSON { - uri: string - } - interface ClientLogin { - token: string - uri: string - } - interface ClientSchema { - byDoctype: TDoctype - client: Client - } - - export class Client { - appMetadata: { version: string; slug: string } - options: ClientLogin - idCounter: number - isLogged: boolean - instanceOptions: ClientInstanceOpts - links: unknown - chain: unknown - schema: unknown - plugins: { realtime: TRealtimePlugin; [key: string]: unknown } - - reducer(): any - setStore(store: any) - - /** - * A plugin is a class whose constructor receives the client as first argument. - * The main mean of interaction with the client should be with events - * like "login"/"logout". - * - * The plugin system is meant to encourage separation of concerns, modularity - * and testability : instead of registering events at module level, please - * create a plugin that subscribes to events. - * - * Plugin instances are stored internally in the `plugins` attribute of the client - * and can be accessed via this mean. A plugin class must have the attribute - * `pluginName` that will be use as the key in the `plugins` object. - * - * Two plugins with the same `pluginName` cannot co-exist. - * - * @example - * ``` - * class AlertPlugin { - * constructor(client, options) { - * this.client = client - * this.options = options - * this.handleLogin = this.handleLogin.bind(this) - * this.handleLogout = this.handleLogout.bind(this) - * this.client.on("login", this.handleLogin) - * this.client.on("logout", this.handleLogout) - * } - * - * handleLogin() { - * alert(this.options.onLoginAlert) - * } - * - * handleLogout() { - * alert(this.options.onLogoutAlert) - * } - * } - * - * AlertPlugin.pluginName = 'alerts' - * - * client.registerPlugin(AlertPlugin, { - * onLoginAlert: 'client has logged in !', - * onLogoutAlert: 'client has logged out !' - * }) - * - * // the instance of the plugin is accessible via - * client.plugins.alerts - * ``` - */ - registerPlugin(Plugin: RealtimePlugin | unknown, options?: unknown) - - /** - * Notify the links that they can start and set isLogged to true. - * - * On mobile, where url/token are set after instantiation, use this method - * to set the token and uri via options. - * - * Emits - * - * - "beforeLogin" at the beginning, before links have been set up - * - "login" when the client is fully logged in and links have been set up - * - * @param {object} options - Options - * @param {string} options.token - If passed, the token is set on the client - * @param {string} options.uri - If passed, the uri is set on the client - * @returns {Promise} - Resolves when all links have been setup and client is fully logged in - * - */ - login(options: ClientLogin): Promise<unknown> - - /** - * Logs out the client and reset all the links - * - * Emits - * - * - "beforeLogout" at the beginning, before links have been reset - * - "login" when the client is fully logged out and links have been reset - * - * @returns {Promise} - Resolves when all links have been reset and client is fully logged out - */ - logout(): Promise<unknown> - - /** - * Forwards to a stack client instance and returns - * a [DocumentCollection]{@link https://docs.cozy.io/en/cozy-client/api/cozy-stack-client/#DocumentCollection} instance. - * - * @param {string} doctype - The collection doctype. - * @returns {CozyStackClient.DocumentCollection} - Collection corresponding to the doctype - */ - collection(doctype: TDoctype): CozyStackClient.AllCollections - - /** - * Fetches an endpoint in an authorized way. - * - * @param {string} method The HTTP method. - * @param {string} path The URI. - * @param {object} body The payload. - * @param {object} opts Options for fetch - * @returns {Promise} - * @throws {FetchError} - */ - fetch( - method: string, - path: string, - body: unknown, - options?: unknown - ): Promise<unknown> - - find(doctype: string, selector?: MongoSelector): QueryDefinition - get(doctype: TDoctype, id: string): unknown - validate<D>(document: D): unknown - save<D, M = undefined>( - documentType: D, - mutationOptions?: M - ): Promise<QueryResult<T, I>> - - /** - * Creates a list of mutations to execute to create a document and its relationships. - * - * ```js - * const baseDoc = { _type: 'io.cozy.todo', label: 'Go hiking' } - * // relations can be arrays or single objects - * const relationships = { - * attachments: [{ _id: 12345, _type: 'io.cozy.files' }, { _id: 6789, _type: 'io.cozy.files' }], - * bills: { _id: 9999, _type: 'io.cozy.bills' } - * } - * client.getDocumentSavePlan(baseDoc, relationships) - * ``` - * - * @param {object} document The base document to create - * @param {object} relationships The list of relationships to add, as a dictionnary. Keys should be relationship names and values the documents to link. - * @returns {Mutation[]} One or more mutation to execute - */ - getDocumentSavePlan<D>(document: D, relationships: unknown) - triggerHook<D>(name: string, document: D): unknown - - /** - * Destroys a document. {before,after}:destroy hooks will be fired. - * - * @param {Document} document - Document to be deleted - * @returns {Document} The document that has been deleted - */ - destroy<D>(document: D): Promise<QueryResult<T, I>> - upload(file: File, dirPath: string, mutationOptions?: unknown) - ensureQueryExists( - queryId: string, - queryDefinition: QueryDefinition - ): unknown - - /** - * Executes a query and returns its results. - * - * Results from the query will be saved internally and can be retrieved via - * `getQueryFromState` or directly using `<Query />`. `<Query />` automatically - * executes its query when mounted if no fetch policy has been indicated. - * - * @param {QueryDefinition} queryDefinition - Definition that will be executed - * @param {string} options - Options - * @param {string} options.as - Names the query so it can be reused (by multiple components for example) - * @param {string} options.fetchPolicy - Fetch policy to bypass fetching based on what's already inside the state. See "Fetch policies" - * @returns {QueryResult} - */ - query( - queryDefinition: QueryDefinition, - { update, ...options }?: unknown - ): Promise<QueryResult<T, I>> - - /** - * Will fetch all documents for a `queryDefinition`, automatically fetching more - * documents if the total of documents is superior to the pagination limit. Can - * result in a lot of network requests. - * - * @param {QueryDefinition} queryDefinition - Definition to be executed - * @param {object} options - Options to the query - * @returns {Array} All documents matching the query - */ - queryAll( - queryDefinition: QueryDefinition, - options: object - ): Promise<QueryResult<T, I>> - makeObservableQuery( - queryDefinition: QueryDefinition, - options?: unknown - ): unknown - create<D>( - doctype: TDoctype, - entry: D, - relationships?: unknown, - options?: unknown - ): Promise<QueryResult<T, I>> - getStackClient(): ClientStackClient - getInstanceOptions(): ClientInstanceOpts - toJSON(): ClientToJSON - - /** - * Returns documents with their relationships resolved according to their schema. - * If related documents are not in the store, they will not be fetched automatically. - * Instead, the relationships will have null documents. - * - * @param {string} doctype - Doctype of the documents being hydrated - * @param {Array<Document>} documents - Documents to be hydrated - * @returns {Array<HydratedDocument>} - */ - hydrateDocuments<D>( - doctype: TDoctype, - documents: Array<D> - ): Array<HydratedDocument> - - /** - * Resolves relationships on a document. - * - * The original document is kept in the target attribute of - * the relationship - * - * @param {Document} document for which relationships must be resolved - * @param {Schema} schemaArg for the document doctype - * @returns {HydratedDocument} - */ - hydrateDocument<D>(document: D, schemaArg?: TDoctype): HydratedDocument - } - - class CCozyClient { - constructor(n: unknown): Client - } - const CozyClient: { - new (n: unknown): Client - } = CCozyClient - export default CozyClient - - export type HydratedDoc = any - - // FIX BEGIN :: Types temporary - export class HasMany { - /** - * Sets a relationship item with the relationship name and id - * - * @param {object} doc - Document to be updated - * @param {string} relName - Name of the relationship - * @param {string} relItemId - Id of the relationship item - * @param {object} relItemAttrs - Attributes to be set (at least _id and _type) - */ - static setHasManyItem<D, R>( - doc: D, - relName: string, - relItemId: string, - relItemAttrs: Relation - ): R - - /** - * Gets a relationship item with the relationship name and id - * - * @param {object} doc - Document to be updated - * @param {string} relName - Name of the relationship - * @param {string} relItemId - Id of the relationship item - */ - static getHasManyItem<D, R>(doc: D, relName: string, relItemId: string): R - - /** - * Updates a relationship item with the relationship name and id - * - * @param {object} doc - Document to be updated - * @param {string} relName - Name of the relationship - * @param {string} relItemId - Id of the relationship item - * @param {Function} updater - receives the current relationship item and should - * return an updated version. Merge should be used in the updater - * if previous relationship item fields are to be kept. - */ - static updateHasManyItem<D, R>( - doc: D, - relName: string, - relItemId: string, - updater: (relItem: Relation) => Relation - ): Promise<QueryResult<R>> - } - // FIX END -} +import * as CozyStackClient from 'cozy-stack-client' +import { TRealtimePlugin, RealtimePlugin } from 'cozy-realtime' +import { TDoctype } from 'doctypes' +import { CozyMetadata, Relation } from 'models' + +declare module 'cozy-client' { + /** + * @typedef {object} HydratedDocument + */ + + export const CozyProvider: React.FC<{ client: Client; store?: any }> + + export function useClient(): Client + export function Q(doctype: TDoctype): QueryDefinition + + export type SortOptions = { [field: string]: 'asc' | 'desc' } + export type QueryDefinition = { + checkSortOrder(opts: { + sort: SortOptions + selector: unknown + indexedFields: unknown + }): QueryDefinition + getById(id: string): QueryDefinition + getByIds(ids: Array<string>): QueryDefinition + include(relations: Array<string>): QueryDefinition + indexFields(indexedFields: Array<string>): QueryDefinition + limitBy(limit: number): QueryDefinition + offset(skip: number): QueryDefinition + offsetBookmark(bookmark: string): QueryDefinition + offsetCursor(cursor): QueryDefinition + referencedBy(document: unknown): QueryDefinition + select(field: Array<string> | undefined): QueryDefinition + sortBy(sort: Array<SortOptions>): QueryDefinition + where(selector: MongoSelector): QueryDefinition + } + export type QueryResult<T, I = undefined> = { + bookmark: string + next: boolean + meta?: { count: number } + skip: number + data: T + included?: I + } + + export interface MongoSelector { + [field: unknown]: unknown + } + export interface AllQueryOptions { + bookmark?: string + keys?: unknown + limit?: number + skip?: number + } + export interface FindQueryOptions { + bookmark?: string + fields?: Array<string> + indexId?: string + limit?: number + skip?: number + sort?: SortOptions[] + } + interface ClientInstanceOpts { + cozyAppEditor: string + cozyAppName: string + cozyAppNamePrefix: string + cozyAppSlug: string + cozyDomain: string + cozyIconPath: string + cozyLocale: string + cozyToken: string + } + interface ClientToJSON { + uri: string + } + interface ClientLogin { + token: string + uri: string + } + interface ClientSchema { + byDoctype: TDoctype + client: Client + } + + export class Client { + appMetadata: { version: string; slug: string } + options: ClientLogin + idCounter: number + isLogged: boolean + instanceOptions: ClientInstanceOpts + links: unknown + chain: unknown + schema: unknown + plugins: { realtime: TRealtimePlugin; [key: string]: unknown } + + reducer(): any + setStore(store: any) + + /** + * A plugin is a class whose constructor receives the client as first argument. + * The main mean of interaction with the client should be with events + * like "login"/"logout". + * + * The plugin system is meant to encourage separation of concerns, modularity + * and testability : instead of registering events at module level, please + * create a plugin that subscribes to events. + * + * Plugin instances are stored internally in the `plugins` attribute of the client + * and can be accessed via this mean. A plugin class must have the attribute + * `pluginName` that will be use as the key in the `plugins` object. + * + * Two plugins with the same `pluginName` cannot co-exist. + * + * @example + * ``` + * class AlertPlugin { + * constructor(client, options) { + * this.client = client + * this.options = options + * this.handleLogin = this.handleLogin.bind(this) + * this.handleLogout = this.handleLogout.bind(this) + * this.client.on("login", this.handleLogin) + * this.client.on("logout", this.handleLogout) + * } + * + * handleLogin() { + * alert(this.options.onLoginAlert) + * } + * + * handleLogout() { + * alert(this.options.onLogoutAlert) + * } + * } + * + * AlertPlugin.pluginName = 'alerts' + * + * client.registerPlugin(AlertPlugin, { + * onLoginAlert: 'client has logged in !', + * onLogoutAlert: 'client has logged out !' + * }) + * + * // the instance of the plugin is accessible via + * client.plugins.alerts + * ``` + */ + registerPlugin(Plugin: RealtimePlugin | unknown, options?: unknown) + + /** + * Notify the links that they can start and set isLogged to true. + * + * On mobile, where url/token are set after instantiation, use this method + * to set the token and uri via options. + * + * Emits + * + * - "beforeLogin" at the beginning, before links have been set up + * - "login" when the client is fully logged in and links have been set up + * + * @param {object} options - Options + * @param {string} options.token - If passed, the token is set on the client + * @param {string} options.uri - If passed, the uri is set on the client + * @returns {Promise} - Resolves when all links have been setup and client is fully logged in + * + */ + login(options: ClientLogin): Promise<unknown> + + /** + * Logs out the client and reset all the links + * + * Emits + * + * - "beforeLogout" at the beginning, before links have been reset + * - "login" when the client is fully logged out and links have been reset + * + * @returns {Promise} - Resolves when all links have been reset and client is fully logged out + */ + logout(): Promise<unknown> + + /** + * Forwards to a stack client instance and returns + * a [DocumentCollection]{@link https://docs.cozy.io/en/cozy-client/api/cozy-stack-client/#DocumentCollection} instance. + * + * @param {string} doctype - The collection doctype. + * @returns {CozyStackClient.DocumentCollection} - Collection corresponding to the doctype + */ + collection(doctype: TDoctype): CozyStackClient.AllCollections + + /** + * Fetches an endpoint in an authorized way. + * + * @param {string} method The HTTP method. + * @param {string} path The URI. + * @param {object} body The payload. + * @param {object} opts Options for fetch + * @returns {Promise} + * @throws {FetchError} + */ + fetch( + method: string, + path: string, + body: unknown, + options?: unknown + ): Promise<unknown> + + find(doctype: string, selector?: MongoSelector): QueryDefinition + get(doctype: TDoctype, id: string): unknown + validate<D>(document: D): unknown + save<D, M = undefined>( + documentType: D, + mutationOptions?: M + ): Promise<QueryResult<T, I>> + + /** + * Creates a list of mutations to execute to create a document and its relationships. + * + * ```js + * const baseDoc = { _type: 'io.cozy.todo', label: 'Go hiking' } + * // relations can be arrays or single objects + * const relationships = { + * attachments: [{ _id: 12345, _type: 'io.cozy.files' }, { _id: 6789, _type: 'io.cozy.files' }], + * bills: { _id: 9999, _type: 'io.cozy.bills' } + * } + * client.getDocumentSavePlan(baseDoc, relationships) + * ``` + * + * @param {object} document The base document to create + * @param {object} relationships The list of relationships to add, as a dictionnary. Keys should be relationship names and values the documents to link. + * @returns {Mutation[]} One or more mutation to execute + */ + getDocumentSavePlan<D>(document: D, relationships: unknown) + triggerHook<D>(name: string, document: D): unknown + + /** + * Destroys a document. {before,after}:destroy hooks will be fired. + * + * @param {Document} document - Document to be deleted + * @returns {Document} The document that has been deleted + */ + destroy<D>(document: D): Promise<QueryResult<T, I>> + upload(file: File, dirPath: string, mutationOptions?: unknown) + ensureQueryExists( + queryId: string, + queryDefinition: QueryDefinition + ): unknown + + /** + * Executes a query and returns its results. + * + * Results from the query will be saved internally and can be retrieved via + * `getQueryFromState` or directly using `<Query />`. `<Query />` automatically + * executes its query when mounted if no fetch policy has been indicated. + * + * @param {QueryDefinition} queryDefinition - Definition that will be executed + * @param {string} options - Options + * @param {string} options.as - Names the query so it can be reused (by multiple components for example) + * @param {string} options.fetchPolicy - Fetch policy to bypass fetching based on what's already inside the state. See "Fetch policies" + * @returns {QueryResult} + */ + query( + queryDefinition: QueryDefinition, + { update, ...options }?: unknown + ): Promise<QueryResult<T, I>> + + /** + * Will fetch all documents for a `queryDefinition`, automatically fetching more + * documents if the total of documents is superior to the pagination limit. Can + * result in a lot of network requests. + * + * @param {QueryDefinition} queryDefinition - Definition to be executed + * @param {object} options - Options to the query + * @returns {Array} All documents matching the query + */ + queryAll( + queryDefinition: QueryDefinition, + options: object + ): Promise<QueryResult<T, I>> + makeObservableQuery( + queryDefinition: QueryDefinition, + options?: unknown + ): unknown + create<D>( + doctype: TDoctype, + entry: D, + relationships?: unknown, + options?: unknown + ): Promise<QueryResult<T, I>> + getStackClient(): ClientStackClient + getInstanceOptions(): ClientInstanceOpts + toJSON(): ClientToJSON + + /** + * Returns documents with their relationships resolved according to their schema. + * If related documents are not in the store, they will not be fetched automatically. + * Instead, the relationships will have null documents. + * + * @param {string} doctype - Doctype of the documents being hydrated + * @param {Array<Document>} documents - Documents to be hydrated + * @returns {Array<HydratedDocument>} + */ + hydrateDocuments<D>( + doctype: TDoctype, + documents: Array<D> + ): Array<HydratedDocument> + + /** + * Resolves relationships on a document. + * + * The original document is kept in the target attribute of + * the relationship + * + * @param {Document} document for which relationships must be resolved + * @param {Schema} schemaArg for the document doctype + * @returns {HydratedDocument} + */ + hydrateDocument<D>(document: D, schemaArg?: TDoctype): HydratedDocument + } + + class CCozyClient { + constructor(n: unknown): Client + } + const CozyClient: { + new (n: unknown): Client + } = CCozyClient + export default CozyClient + + export type HydratedDoc = any + + // FIX BEGIN :: Types temporary + export class HasMany { + /** + * Sets a relationship item with the relationship name and id + * + * @param {object} doc - Document to be updated + * @param {string} relName - Name of the relationship + * @param {string} relItemId - Id of the relationship item + * @param {object} relItemAttrs - Attributes to be set (at least _id and _type) + */ + static setHasManyItem<D, R>( + doc: D, + relName: string, + relItemId: string, + relItemAttrs: Relation + ): R + + /** + * Gets a relationship item with the relationship name and id + * + * @param {object} doc - Document to be updated + * @param {string} relName - Name of the relationship + * @param {string} relItemId - Id of the relationship item + */ + static getHasManyItem<D, R>(doc: D, relName: string, relItemId: string): R + + /** + * Updates a relationship item with the relationship name and id + * + * @param {object} doc - Document to be updated + * @param {string} relName - Name of the relationship + * @param {string} relItemId - Id of the relationship item + * @param {Function} updater - receives the current relationship item and should + * return an updated version. Merge should be used in the updater + * if previous relationship item fields are to be kept. + */ + static updateHasManyItem<D, R>( + doc: D, + relName: string, + relItemId: string, + updater: (relItem: Relation) => Relation + ): Promise<QueryResult<R>> + } + // FIX END +} diff --git a/src/cozy-doctypes.d.ts b/src/types/cozy-doctypes.d.ts similarity index 96% rename from src/cozy-doctypes.d.ts rename to src/types/cozy-doctypes.d.ts index a81ef94042ff90970b2d3e767a4eae4258a427aa..36f618e3ae6a0af006a00f3df371740c2fd0ba02 100644 --- a/src/cozy-doctypes.d.ts +++ b/src/types/cozy-doctypes.d.ts @@ -1 +1 @@ -declare module 'cozy-doctypes' +declare module 'cozy-doctypes' diff --git a/src/cozy-harvest-lib.d.ts b/src/types/cozy-harvest-lib.d.ts similarity index 98% rename from src/cozy-harvest-lib.d.ts rename to src/types/cozy-harvest-lib.d.ts index 6322ea7904223decd70f287ceb5d859bc3708e0d..b9454d57f149f34ade50fffba8cf35656e66e6ce 100644 --- a/src/cozy-harvest-lib.d.ts +++ b/src/types/cozy-harvest-lib.d.ts @@ -1,7 +1,7 @@ -declare module 'cozy-harvest-lib/dist/connections/accounts' -declare module 'cozy-harvest-lib/dist/helpers/accounts' -declare module 'cozy-harvest-lib/dist/connections/triggers' -declare module 'cozy-harvest-lib/dist/helpers/triggers' -declare module 'cozy-harvest-lib/dist/models/ConnectionFlow' -declare module 'cozy-harvest-lib/dist/components/OAuthWindow' -declare module 'cozy-harvest-lib/dist/helpers/oauth' +declare module 'cozy-harvest-lib/dist/connections/accounts' +declare module 'cozy-harvest-lib/dist/helpers/accounts' +declare module 'cozy-harvest-lib/dist/connections/triggers' +declare module 'cozy-harvest-lib/dist/helpers/triggers' +declare module 'cozy-harvest-lib/dist/models/ConnectionFlow' +declare module 'cozy-harvest-lib/dist/components/OAuthWindow' +declare module 'cozy-harvest-lib/dist/helpers/oauth' diff --git a/src/cozy-logger.d.ts b/src/types/cozy-logger.d.ts similarity index 94% rename from src/cozy-logger.d.ts rename to src/types/cozy-logger.d.ts index c0c144e848d98c4ba4acf12e6ec1372ea01eeb8c..e0c8fde8b642e7c932eddc2f7820b719e55afd12 100644 --- a/src/cozy-logger.d.ts +++ b/src/types/cozy-logger.d.ts @@ -1,10 +1,10 @@ -declare module 'cozy-loggers' - -export function namespace(namespace: string): log - -export function log( - type: string, - message: string, - label: string, - namespace: string -): void +declare module 'cozy-loggers' + +export function namespace(namespace: string): log + +export function log( + type: string, + message: string, + label: string, + namespace: string +): void diff --git a/src/cozy-ui.d.ts b/src/types/cozy-ui.d.ts similarity index 96% rename from src/cozy-ui.d.ts rename to src/types/cozy-ui.d.ts index 9c0cb4f275420c5fe7aed4f849b4e23ac14ccad6..01a043d2956e291ddb1bc827f34429d86713bbb8 100644 --- a/src/cozy-ui.d.ts +++ b/src/types/cozy-ui.d.ts @@ -1,36 +1,36 @@ -/* eslint-disable @typescript-eslint/interface-name-prefix */ -/* eslint-disable @typescript-eslint/no-explicit-any */ -declare module 'cozy-ui/transpiled/react/Icon' -declare module 'cozy-ui/transpiled/react/Spinner' -declare module 'cozy-ui/transpiled/react/Layout' - -declare module 'cozy-ui/transpiled/react/I18n' { - interface IPropsIcon { - icon?: string - width?: string | number - height?: string | number - color?: string - className?: string - preserveColor?: string - rotate?: string - size?: string | number - spin?: any - [key: string]: any - } - interface IuseI18n { - t: (key: string, opt?: any) => string - f: (date: Date, format: string) => string - lang: string - } - - export function useI18n(): IuseI18n - export function Icon( - props: IPropsIcon - ): React.CElement<any, React.Component<any, any, any>> - export const I18n: any - - export function initTranslation( - userLocal: string, - cb: (lang: string) => string - ) -} +/* eslint-disable @typescript-eslint/interface-name-prefix */ +/* eslint-disable @typescript-eslint/no-explicit-any */ +declare module 'cozy-ui/transpiled/react/Icon' +declare module 'cozy-ui/transpiled/react/Spinner' +declare module 'cozy-ui/transpiled/react/Layout' + +declare module 'cozy-ui/transpiled/react/I18n' { + interface IPropsIcon { + icon?: string + width?: string | number + height?: string | number + color?: string + className?: string + preserveColor?: string + rotate?: string + size?: string | number + spin?: any + [key: string]: any + } + interface IuseI18n { + t: (key: string, opt?: any) => string + f: (date: Date, format: string) => string + lang: string + } + + export function useI18n(): IuseI18n + export function Icon( + props: IPropsIcon + ): React.CElement<any, React.Component<any, any, any>> + export const I18n: any + + export function initTranslation( + userLocal: string, + cb: (lang: string) => string + ) +} diff --git a/src/custom.d.ts b/src/types/custom.d.ts similarity index 95% rename from src/custom.d.ts rename to src/types/custom.d.ts index 9c3a50175ffad9a357b86574d04428527d0ee49e..0016563a7edbf81abbfd0a222b69e62df2fe09a1 100644 --- a/src/custom.d.ts +++ b/src/types/custom.d.ts @@ -1,8 +1,8 @@ -declare module '*.png' { - const content: string - export default content -} -declare module '*.svg' { - const content: string - export default content -} +declare module '*.png' { + const content: string + export default content +} +declare module '*.svg' { + const content: string + export default content +} diff --git a/src/react-swipeable-views-utils.d.ts b/src/types/react-swipeable-views-utils.d.ts similarity index 96% rename from src/react-swipeable-views-utils.d.ts rename to src/types/react-swipeable-views-utils.d.ts index 8495e5a54f1a1c88d2ef0b7c993a18b756c197cd..589e1484e206a6516ac9046c7f7b5855352a9a94 100644 --- a/src/react-swipeable-views-utils.d.ts +++ b/src/types/react-swipeable-views-utils.d.ts @@ -1,42 +1,42 @@ -declare module 'react-swipeable-views-utils' { - import ReactSwipeableViews from 'react-swipeable-views' - - export interface VirtualizedSlideRendererParams { - index: number - key: number - } - - interface VirtualizedComponentProps { - index?: number - onChangeIndex?: (currentIndex: number, prevIndex: number) => void - onTransitionEnd?: () => void - overscanSlideAfter?: number - overscanSlideBefore?: number - slideCount?: number - slideRenderer?: (params: VirtualizedSlideRendererParams) => JSX.Element - enableMouseEvents?: boolean - onSwitching?: (() => void) | null - axis?: AxisType - } - - interface VirtualizedComponentState { - indexContainer: number - indexStart: number - indexStop: number - } - - class VirtualizedComponent extends React.Component< - VirtualizedComponentProps, - VirtualizedComponentState - > { - handleChangeIndex(indexContainer: number, indexLatest: number): void - handleTransitionEnd(): void - setIndex(index: number, indexContainer: number, indexDiff: number): void - setWindow(index: number): void - } - - export function virtualize( - component: typeof ReactSwipeableViews - ): typeof VirtualizedComponent - export default virtualize -} +declare module 'react-swipeable-views-utils' { + import ReactSwipeableViews from 'react-swipeable-views' + + export interface VirtualizedSlideRendererParams { + index: number + key: number + } + + interface VirtualizedComponentProps { + index?: number + onChangeIndex?: (currentIndex: number, prevIndex: number) => void + onTransitionEnd?: () => void + overscanSlideAfter?: number + overscanSlideBefore?: number + slideCount?: number + slideRenderer?: (params: VirtualizedSlideRendererParams) => JSX.Element + enableMouseEvents?: boolean + onSwitching?: (() => void) | null + axis?: AxisType + } + + interface VirtualizedComponentState { + indexContainer: number + indexStart: number + indexStop: number + } + + class VirtualizedComponent extends React.Component< + VirtualizedComponentProps, + VirtualizedComponentState + > { + handleChangeIndex(indexContainer: number, indexLatest: number): void + handleTransitionEnd(): void + setIndex(index: number, indexContainer: number, indexDiff: number): void + setWindow(index: number): void + } + + export function virtualize( + component: typeof ReactSwipeableViews + ): typeof VirtualizedComponent + export default virtualize +} diff --git a/src/react-swipeable-views.d.ts b/src/types/react-swipeable-views.d.ts similarity index 96% rename from src/react-swipeable-views.d.ts rename to src/types/react-swipeable-views.d.ts index e1c55ef3bef6bda49c7b1a32a6e8c29838abaaaf..3dc91701611e64584b1c13d2f1c02a7278c5fc23 100644 --- a/src/react-swipeable-views.d.ts +++ b/src/types/react-swipeable-views.d.ts @@ -1,64 +1,64 @@ -declare module 'react-swipeable-views' { - import * as React from 'react' - - export type OnChangeIndexCallback = ( - index: number, - indexLatest: number - ) => void - - export type OnTransitionEndCallback = () => void - - export type OnSwitchingCallback = ( - index: number, - type: OnSwitchingCallbackTypeDescriptor - ) => void - - export type OnSwitchingCallbackTypeDescriptor = 'move' | 'end' - - export type AxisType = 'x' | 'x-reverse' | 'y' | 'y-reverse' - - export interface SpringConfig { - duration: string - easeFunction: string - delay: string - } - - export interface SwipeableViewsProps extends React.HTMLProps<HTMLDivElement> { - animateHeight?: boolean - animateTransitions?: boolean - axis?: AxisType - containerStyle?: React.CSSProperties - disabled?: boolean - /* - * This is the config used to disable lazy loading, if true it will render all the views in first rendering. - */ - disableLazyLoading?: boolean - enableMouseEvents?: boolean - hysteresis?: number - ignoreNativeScroll?: boolean - index?: number - onChangeIndex?: OnChangeIndexCallback - onSwitching?: OnSwitchingCallback - onTransitionEnd?: OnTransitionEndCallback - resistance?: boolean - style?: React.CSSProperties - slideStyle?: React.CSSProperties - springConfig?: SpringConfig - slideClassName?: string - threshold?: number - } - - export interface SwipeableViewsState { - indexCurrent?: number - indexLatest?: number - isDragging?: boolean - isFirstRender?: boolean - heightLatest?: number - displaySameSlide?: boolean - } - - export default class SwipeableViews extends React.Component< - SwipeableViewsProps, - SwipeableViewsState - > {} -} +declare module 'react-swipeable-views' { + import * as React from 'react' + + export type OnChangeIndexCallback = ( + index: number, + indexLatest: number + ) => void + + export type OnTransitionEndCallback = () => void + + export type OnSwitchingCallback = ( + index: number, + type: OnSwitchingCallbackTypeDescriptor + ) => void + + export type OnSwitchingCallbackTypeDescriptor = 'move' | 'end' + + export type AxisType = 'x' | 'x-reverse' | 'y' | 'y-reverse' + + export interface SpringConfig { + duration: string + easeFunction: string + delay: string + } + + export interface SwipeableViewsProps extends React.HTMLProps<HTMLDivElement> { + animateHeight?: boolean + animateTransitions?: boolean + axis?: AxisType + containerStyle?: React.CSSProperties + disabled?: boolean + /* + * This is the config used to disable lazy loading, if true it will render all the views in first rendering. + */ + disableLazyLoading?: boolean + enableMouseEvents?: boolean + hysteresis?: number + ignoreNativeScroll?: boolean + index?: number + onChangeIndex?: OnChangeIndexCallback + onSwitching?: OnSwitchingCallback + onTransitionEnd?: OnTransitionEndCallback + resistance?: boolean + style?: React.CSSProperties + slideStyle?: React.CSSProperties + springConfig?: SpringConfig + slideClassName?: string + threshold?: number + } + + export interface SwipeableViewsState { + indexCurrent?: number + indexLatest?: number + isDragging?: boolean + isFirstRender?: boolean + heightLatest?: number + displaySameSlide?: boolean + } + + export default class SwipeableViews extends React.Component< + SwipeableViewsProps, + SwipeableViewsState + > {} +} diff --git a/src/utils/date.spec.ts b/src/utils/date.spec.ts index c4539f41e02fa6cc1a6a9753bc2bfa92ddcfc6fb..ea24f0a3f3eabb5c1e5e7c9c5dcd1ff1c866ebf8 100644 --- a/src/utils/date.spec.ts +++ b/src/utils/date.spec.ts @@ -1,464 +1,464 @@ -import { FluidType } from 'enum/fluid.enum' -import { TimeStep } from 'enum/timeStep.enum' -import { DateTime } from 'luxon' -import { Dataload } from 'models' -import { graphData } from '../../test/__mocks__/datachartData.mock' -import { - compareDates, - isLastDateReached, - isLastPeriodReached, - getLagDays, - convertDateToMonthString, - convertDateToShortDateString, - getActualAnalysisDate, - convertDateToMonthYearString, -} from './date' - -describe('date utils', () => { - describe('compareDates test', () => { - const datePrevious = DateTime.fromObject({ year: 2020, month: 11, day: 1 }) - const dateLatter = DateTime.fromObject({ year: 2020, month: 11, day: 2 }) - - it('should return -1 if date is previous that the second one', () => { - const result = compareDates(datePrevious, dateLatter) - expect(result).toBe(-1) - }) - - it('should return 1 if the date is latter that the second one', () => { - const result = compareDates(dateLatter, datePrevious) - expect(result).toBe(1) - }) - }) - - describe('isLastDateReached test', () => { - describe('case HALF_AN_Hour', () => { - const timeStep = TimeStep.HALF_AN_HOUR - - it('should return true if date is latter that now', () => { - const result = isLastDateReached( - DateTime.local() - .setZone('utc', { - keepLocalTime: true, - }) - .plus({ days: 1 }), - timeStep - ) - expect(result).toBe(true) - }) - - it('should return false if date is previous that now', () => { - const result = isLastDateReached( - DateTime.local() - .setZone('utc', { - keepLocalTime: true, - }) - .minus({ days: 1 }), - timeStep - ) - expect(result).toBe(false) - }) - }) - - describe('case WEEK', () => { - const timeStep = TimeStep.WEEK - - it('should return true if date is latter that now', () => { - const result = isLastDateReached( - DateTime.local() - .setZone('utc', { - keepLocalTime: true, - }) - .plus({ days: 1 }), - timeStep - ) - expect(result).toBe(true) - }) - - it('should return false if date is previous that now', () => { - const result = isLastDateReached( - DateTime.local() - .setZone('utc', { - keepLocalTime: true, - }) - .minus({ days: 1 }), - timeStep - ) - expect(result).toBe(false) - }) - }) - - describe('case DAY', () => { - const timeStep = TimeStep.DAY - - it('should return true if date is latter that now', () => { - const result = isLastDateReached( - DateTime.local() - .setZone('utc', { - keepLocalTime: true, - }) - .plus({ days: 1 }), - timeStep - ) - expect(result).toBe(true) - }) - - it('should return false if date is previous that now', () => { - const result = isLastDateReached( - DateTime.local() - .setZone('utc', { - keepLocalTime: true, - }) - .minus({ days: 1 }), - timeStep - ) - expect(result).toBe(false) - }) - }) - - describe('case MONTH', () => { - const timeStep = TimeStep.MONTH - - it('should return true if date is latter that now', () => { - const result = isLastDateReached( - DateTime.local() - .setZone('utc', { - keepLocalTime: true, - }) - .plus({ months: 1 }), - timeStep - ) - expect(result).toBe(true) - }) - - it('should return false if date is previous that now', () => { - const result = isLastDateReached( - DateTime.local() - .setZone('utc', { - keepLocalTime: true, - }) - .minus({ months: 1 }), - timeStep - ) - expect(result).toBe(false) - }) - }) - - describe('case YEAR', () => { - const timeStep = TimeStep.YEAR - - it('should return true if date is latter that now', () => { - const result = isLastDateReached( - DateTime.local() - .setZone('utc', { - keepLocalTime: true, - }) - .plus({ years: 1 }), - timeStep - ) - expect(result).toBe(true) - }) - - it('should return false if date is previous that now', () => { - const result = isLastDateReached( - DateTime.local() - .setZone('utc', { - keepLocalTime: true, - }) - .minus({ years: 1 }), - timeStep - ) - expect(result).toBe(false) - }) - }) - - describe('default', () => { - it('should return false', () => { - const result = isLastDateReached( - DateTime.local() - .setZone('utc', { - keepLocalTime: true, - }) - .minus({ years: 1 }), - 0 - ) - expect(result).toBe(false) - }) - }) - }) - - describe('IsLastPeriodReached test', () => { - describe('case HALF_AN_HOUR', () => { - const timeStep = TimeStep.HALF_AN_HOUR - - it('should return false when date is previous to now + 1 day', () => { - const result = isLastPeriodReached( - DateTime.local() - .setZone('utc', { - keepLocalTime: true, - }) - .minus({ days: 1 }), - timeStep - ) - expect(result).toBe(false) - }) - - it('should return true when date is latter to date + 1 day', () => { - const result = isLastPeriodReached( - DateTime.local() - .setZone('utc', { - keepLocalTime: true, - }) - .plus({ days: 1 }), - timeStep - ) - expect(result).toBe(true) - }) - }) - - describe('case WEEK', () => { - const timeStep = TimeStep.WEEK - - it('should return false when date is previous to week + 1 day', () => { - const result = isLastPeriodReached( - DateTime.local() - .setZone('utc', { - keepLocalTime: true, - }) - .minus({ week: 1 }), - timeStep - ) - expect(result).toBe(false) - }) - - it('should return true when date is latter to week + 1 day', () => { - const result = isLastPeriodReached( - DateTime.local() - .setZone('utc', { - keepLocalTime: true, - }) - .plus({ week: 1 }), - timeStep - ) - expect(result).toBe(true) - }) - }) - - describe('case DAY', () => { - const timeStep = TimeStep.DAY - - it('should return false when date is previous to now + 1 month', () => { - const result = isLastPeriodReached( - DateTime.local() - .setZone('utc', { - keepLocalTime: true, - }) - .minus({ months: 1 }), - timeStep - ) - expect(result).toBe(false) - }) - - it('should return true when date is latter to date + 1 month', () => { - const result = isLastPeriodReached( - DateTime.local() - .setZone('utc', { - keepLocalTime: true, - }) - .plus({ months: 1 }), - timeStep - ) - expect(result).toBe(true) - }) - }) - - describe('case MONTH', () => { - const timeStep = TimeStep.MONTH - - it('should return false when date is previous to now + 1 year', () => { - const result = isLastPeriodReached( - DateTime.local() - .setZone('utc', { - keepLocalTime: true, - }) - .minus({ years: 1 }), - timeStep - ) - expect(result).toBe(false) - }) - - it('should return true when date is latter to date + 1 year', () => { - const result = isLastPeriodReached( - DateTime.local() - .setZone('utc', { - keepLocalTime: true, - }) - .plus({ years: 1 }), - timeStep - ) - expect(result).toBe(true) - }) - }) - - describe('case YEAR', () => { - const timeStep = TimeStep.YEAR - - it('should return false when date is previous to now + 5 year', () => { - const result = isLastPeriodReached( - DateTime.local() - .setZone('utc', { - keepLocalTime: true, - }) - .minus({ years: 5 }), - timeStep - ) - expect(result).toBe(false) - }) - - it('should return true when date is latter to date + 5 year', () => { - const result = isLastPeriodReached( - DateTime.local() - .setZone('utc', { - keepLocalTime: true, - }) - .plus({ years: 5 }), - timeStep - ) - expect(result).toBe(true) - }) - }) - - describe('default', () => { - it('should return false', () => { - const result = isLastPeriodReached( - DateTime.local() - .setZone('utc', { - keepLocalTime: true, - }) - .minus({ years: 1 }), - 0 - ) - expect(result).toBe(false) - }) - }) - }) - - describe('getLagDays test', () => { - it('should return 3 when there is only WATER fluid type', () => { - const result = getLagDays([FluidType.WATER]) - expect(result).toBe(3) - }) - - it('it should return 3 when there are many fuild type including WATER', () => { - const result = getLagDays([FluidType.ELECTRICITY, FluidType.WATER]) - expect(result).toBe(3) - }) - - it('should return 2 hen there is only GAS Fluid Type', () => { - const result = getLagDays([FluidType.GAS]) - expect(result).toBe(2) - }) - - it('it should return 2 when there are many fluid type including GAS and excluding WATER', () => { - const result = getLagDays([FluidType.ELECTRICITY, FluidType.GAS]) - expect(result).toBe(2) - }) - - it('it should return when there is only ELECTRICTY Fluid Type', () => { - const result = getLagDays([FluidType.ELECTRICITY]) - expect(result).toBe(1) - }) - }) - - describe('convertDateToShortDateString test', () => { - const actualData: Dataload[] = graphData.actualData - - it('should return an empty string when the TimePeriod is unknown', () => { - const result = convertDateToShortDateString(null, 99) - expect(result).toBe('') - }) - - describe('should return the correct short date string', () => { - it('case HALF_AN_HOUR', () => { - const result = convertDateToShortDateString( - actualData, - TimeStep.HALF_AN_HOUR - ) - expect(result).toBe('jeudi 01 octobre') - }) - - it('case WEEK', () => { - const result = convertDateToShortDateString(actualData, TimeStep.WEEK) - expect(result).toBe('du 01/10 au 03/10') - }) - - it('case DAY', () => { - const result = convertDateToShortDateString(actualData, TimeStep.DAY) - expect(result).toBe('octobre 2020') - }) - - it('case MONTH', () => { - const result = convertDateToShortDateString(actualData, TimeStep.MONTH) - expect(result).toBe('année 2020') - }) - - it('case YEAR', () => { - const result = convertDateToShortDateString(actualData, TimeStep.YEAR) - expect(result).toBe('de 2020 à 2020') - }) - }) - }) - - describe('convertDateToMonthString test', () => { - it('should return the name of the month with " de " ', () => { - const date = DateTime.fromISO('2020-11-29T23:59:59.999Z', { - zone: 'utc', - }) - const result = convertDateToMonthString(date) - expect(result).toBe(' de novembre') - }) - - it('should return the name of the month with " d\'" ', () => { - const date = DateTime.fromISO('2020-10-29T23:59:59.999Z', { - zone: 'utc', - }) - const result = convertDateToMonthString(date) - expect(result).toBe(" d'octobre") - }) - }) - - describe('convertDateToMonthYearString test', () => { - it('should return the name of the month and the year', () => { - const date = DateTime.fromISO('2020-11-29T23:59:59.999Z', { - zone: 'utc', - }) - const result = convertDateToMonthYearString(date) - expect(result).toBe('novembre 2020') - }) - }) - - describe('getActualAnalysisDate test', () => { - it('should return the 3rd of this month if actual day >= 3', () => { - const now = DateTime.local().setZone('utc', { - keepLocalTime: true, - }) - jest - .spyOn(DateTime, 'local') - .mockReturnValueOnce(now.set({ day: 3, month: 11, year: 2020 })) - const mockDate = now.startOf('day').set({ day: 3, month: 11, year: 2020 }) - const result = getActualAnalysisDate() - expect(result).toEqual(mockDate) - }) - - it('should return the 3rd of previous month if actual day < 3', () => { - const now = DateTime.local().setZone('utc', { - keepLocalTime: true, - }) - jest - .spyOn(DateTime, 'local') - .mockReturnValueOnce(now.set({ day: 2, month: 11, year: 2020 })) - const mockDate = now.startOf('day').set({ day: 3, month: 10, year: 2020 }) - const result = getActualAnalysisDate() - expect(result).toEqual(mockDate) - }) - }) -}) +import { FluidType } from 'enum/fluid.enum' +import { TimeStep } from 'enum/timeStep.enum' +import { DateTime } from 'luxon' +import { Dataload } from 'models' +import { graphData } from '../../tests/__mocks__/datachartData.mock' +import { + compareDates, + isLastDateReached, + isLastPeriodReached, + getLagDays, + convertDateToMonthString, + convertDateToShortDateString, + getActualAnalysisDate, + convertDateToMonthYearString, +} from './date' + +describe('date utils', () => { + describe('compareDates test', () => { + const datePrevious = DateTime.fromObject({ year: 2020, month: 11, day: 1 }) + const dateLatter = DateTime.fromObject({ year: 2020, month: 11, day: 2 }) + + it('should return -1 if date is previous that the second one', () => { + const result = compareDates(datePrevious, dateLatter) + expect(result).toBe(-1) + }) + + it('should return 1 if the date is latter that the second one', () => { + const result = compareDates(dateLatter, datePrevious) + expect(result).toBe(1) + }) + }) + + describe('isLastDateReached test', () => { + describe('case HALF_AN_Hour', () => { + const timeStep = TimeStep.HALF_AN_HOUR + + it('should return true if date is latter that now', () => { + const result = isLastDateReached( + DateTime.local() + .setZone('utc', { + keepLocalTime: true, + }) + .plus({ days: 1 }), + timeStep + ) + expect(result).toBe(true) + }) + + it('should return false if date is previous that now', () => { + const result = isLastDateReached( + DateTime.local() + .setZone('utc', { + keepLocalTime: true, + }) + .minus({ days: 1 }), + timeStep + ) + expect(result).toBe(false) + }) + }) + + describe('case WEEK', () => { + const timeStep = TimeStep.WEEK + + it('should return true if date is latter that now', () => { + const result = isLastDateReached( + DateTime.local() + .setZone('utc', { + keepLocalTime: true, + }) + .plus({ days: 1 }), + timeStep + ) + expect(result).toBe(true) + }) + + it('should return false if date is previous that now', () => { + const result = isLastDateReached( + DateTime.local() + .setZone('utc', { + keepLocalTime: true, + }) + .minus({ days: 1 }), + timeStep + ) + expect(result).toBe(false) + }) + }) + + describe('case DAY', () => { + const timeStep = TimeStep.DAY + + it('should return true if date is latter that now', () => { + const result = isLastDateReached( + DateTime.local() + .setZone('utc', { + keepLocalTime: true, + }) + .plus({ days: 1 }), + timeStep + ) + expect(result).toBe(true) + }) + + it('should return false if date is previous that now', () => { + const result = isLastDateReached( + DateTime.local() + .setZone('utc', { + keepLocalTime: true, + }) + .minus({ days: 1 }), + timeStep + ) + expect(result).toBe(false) + }) + }) + + describe('case MONTH', () => { + const timeStep = TimeStep.MONTH + + it('should return true if date is latter that now', () => { + const result = isLastDateReached( + DateTime.local() + .setZone('utc', { + keepLocalTime: true, + }) + .plus({ months: 1 }), + timeStep + ) + expect(result).toBe(true) + }) + + it('should return false if date is previous that now', () => { + const result = isLastDateReached( + DateTime.local() + .setZone('utc', { + keepLocalTime: true, + }) + .minus({ months: 1 }), + timeStep + ) + expect(result).toBe(false) + }) + }) + + describe('case YEAR', () => { + const timeStep = TimeStep.YEAR + + it('should return true if date is latter that now', () => { + const result = isLastDateReached( + DateTime.local() + .setZone('utc', { + keepLocalTime: true, + }) + .plus({ years: 1 }), + timeStep + ) + expect(result).toBe(true) + }) + + it('should return false if date is previous that now', () => { + const result = isLastDateReached( + DateTime.local() + .setZone('utc', { + keepLocalTime: true, + }) + .minus({ years: 1 }), + timeStep + ) + expect(result).toBe(false) + }) + }) + + describe('default', () => { + it('should return false', () => { + const result = isLastDateReached( + DateTime.local() + .setZone('utc', { + keepLocalTime: true, + }) + .minus({ years: 1 }), + 0 + ) + expect(result).toBe(false) + }) + }) + }) + + describe('IsLastPeriodReached test', () => { + describe('case HALF_AN_HOUR', () => { + const timeStep = TimeStep.HALF_AN_HOUR + + it('should return false when date is previous to now + 1 day', () => { + const result = isLastPeriodReached( + DateTime.local() + .setZone('utc', { + keepLocalTime: true, + }) + .minus({ days: 1 }), + timeStep + ) + expect(result).toBe(false) + }) + + it('should return true when date is latter to date + 1 day', () => { + const result = isLastPeriodReached( + DateTime.local() + .setZone('utc', { + keepLocalTime: true, + }) + .plus({ days: 1 }), + timeStep + ) + expect(result).toBe(true) + }) + }) + + describe('case WEEK', () => { + const timeStep = TimeStep.WEEK + + it('should return false when date is previous to week + 1 day', () => { + const result = isLastPeriodReached( + DateTime.local() + .setZone('utc', { + keepLocalTime: true, + }) + .minus({ week: 1 }), + timeStep + ) + expect(result).toBe(false) + }) + + it('should return true when date is latter to week + 1 day', () => { + const result = isLastPeriodReached( + DateTime.local() + .setZone('utc', { + keepLocalTime: true, + }) + .plus({ week: 1 }), + timeStep + ) + expect(result).toBe(true) + }) + }) + + describe('case DAY', () => { + const timeStep = TimeStep.DAY + + it('should return false when date is previous to now + 1 month', () => { + const result = isLastPeriodReached( + DateTime.local() + .setZone('utc', { + keepLocalTime: true, + }) + .minus({ months: 1 }), + timeStep + ) + expect(result).toBe(false) + }) + + it('should return true when date is latter to date + 1 month', () => { + const result = isLastPeriodReached( + DateTime.local() + .setZone('utc', { + keepLocalTime: true, + }) + .plus({ months: 1 }), + timeStep + ) + expect(result).toBe(true) + }) + }) + + describe('case MONTH', () => { + const timeStep = TimeStep.MONTH + + it('should return false when date is previous to now + 1 year', () => { + const result = isLastPeriodReached( + DateTime.local() + .setZone('utc', { + keepLocalTime: true, + }) + .minus({ years: 1 }), + timeStep + ) + expect(result).toBe(false) + }) + + it('should return true when date is latter to date + 1 year', () => { + const result = isLastPeriodReached( + DateTime.local() + .setZone('utc', { + keepLocalTime: true, + }) + .plus({ years: 1 }), + timeStep + ) + expect(result).toBe(true) + }) + }) + + describe('case YEAR', () => { + const timeStep = TimeStep.YEAR + + it('should return false when date is previous to now + 5 year', () => { + const result = isLastPeriodReached( + DateTime.local() + .setZone('utc', { + keepLocalTime: true, + }) + .minus({ years: 5 }), + timeStep + ) + expect(result).toBe(false) + }) + + it('should return true when date is latter to date + 5 year', () => { + const result = isLastPeriodReached( + DateTime.local() + .setZone('utc', { + keepLocalTime: true, + }) + .plus({ years: 5 }), + timeStep + ) + expect(result).toBe(true) + }) + }) + + describe('default', () => { + it('should return false', () => { + const result = isLastPeriodReached( + DateTime.local() + .setZone('utc', { + keepLocalTime: true, + }) + .minus({ years: 1 }), + 0 + ) + expect(result).toBe(false) + }) + }) + }) + + describe('getLagDays test', () => { + it('should return 3 when there is only WATER fluid type', () => { + const result = getLagDays([FluidType.WATER]) + expect(result).toBe(3) + }) + + it('it should return 3 when there are many fuild type including WATER', () => { + const result = getLagDays([FluidType.ELECTRICITY, FluidType.WATER]) + expect(result).toBe(3) + }) + + it('should return 2 hen there is only GAS Fluid Type', () => { + const result = getLagDays([FluidType.GAS]) + expect(result).toBe(2) + }) + + it('it should return 2 when there are many fluid type including GAS and excluding WATER', () => { + const result = getLagDays([FluidType.ELECTRICITY, FluidType.GAS]) + expect(result).toBe(2) + }) + + it('it should return when there is only ELECTRICTY Fluid Type', () => { + const result = getLagDays([FluidType.ELECTRICITY]) + expect(result).toBe(1) + }) + }) + + describe('convertDateToShortDateString test', () => { + const actualData: Dataload[] = graphData.actualData + + it('should return an empty string when the TimePeriod is unknown', () => { + const result = convertDateToShortDateString(null, 99) + expect(result).toBe('') + }) + + describe('should return the correct short date string', () => { + it('case HALF_AN_HOUR', () => { + const result = convertDateToShortDateString( + actualData, + TimeStep.HALF_AN_HOUR + ) + expect(result).toBe('jeudi 01 octobre') + }) + + it('case WEEK', () => { + const result = convertDateToShortDateString(actualData, TimeStep.WEEK) + expect(result).toBe('du 01/10 au 03/10') + }) + + it('case DAY', () => { + const result = convertDateToShortDateString(actualData, TimeStep.DAY) + expect(result).toBe('octobre 2020') + }) + + it('case MONTH', () => { + const result = convertDateToShortDateString(actualData, TimeStep.MONTH) + expect(result).toBe('année 2020') + }) + + it('case YEAR', () => { + const result = convertDateToShortDateString(actualData, TimeStep.YEAR) + expect(result).toBe('de 2020 à 2020') + }) + }) + }) + + describe('convertDateToMonthString test', () => { + it('should return the name of the month with " de " ', () => { + const date = DateTime.fromISO('2020-11-29T23:59:59.999Z', { + zone: 'utc', + }) + const result = convertDateToMonthString(date) + expect(result).toBe(' de novembre') + }) + + it('should return the name of the month with " d\'" ', () => { + const date = DateTime.fromISO('2020-10-29T23:59:59.999Z', { + zone: 'utc', + }) + const result = convertDateToMonthString(date) + expect(result).toBe(" d'octobre") + }) + }) + + describe('convertDateToMonthYearString test', () => { + it('should return the name of the month and the year', () => { + const date = DateTime.fromISO('2020-11-29T23:59:59.999Z', { + zone: 'utc', + }) + const result = convertDateToMonthYearString(date) + expect(result).toBe('novembre 2020') + }) + }) + + describe('getActualAnalysisDate test', () => { + it('should return the 3rd of this month if actual day >= 3', () => { + const now = DateTime.local().setZone('utc', { + keepLocalTime: true, + }) + jest + .spyOn(DateTime, 'local') + .mockReturnValueOnce(now.set({ day: 3, month: 11, year: 2020 })) + const mockDate = now.startOf('day').set({ day: 3, month: 11, year: 2020 }) + const result = getActualAnalysisDate() + expect(result).toEqual(mockDate) + }) + + it('should return the 3rd of previous month if actual day < 3', () => { + const now = DateTime.local().setZone('utc', { + keepLocalTime: true, + }) + jest + .spyOn(DateTime, 'local') + .mockReturnValueOnce(now.set({ day: 2, month: 11, year: 2020 })) + const mockDate = now.startOf('day').set({ day: 3, month: 10, year: 2020 }) + const result = getActualAnalysisDate() + expect(result).toEqual(mockDate) + }) + }) +}) diff --git a/src/utils/hash.spec.ts b/src/utils/hash.spec.ts index 0ecb357dad24df313b8dae884696998365037d43..22f9a2b752a88d26f31f827d475446faf04c4a21 100644 --- a/src/utils/hash.spec.ts +++ b/src/utils/hash.spec.ts @@ -1,5 +1,5 @@ import { hashFile } from './hash' -import { ecogesturesData } from '../../test/__mocks__/ecogesturesData.mock' +import { ecogesturesData } from '../../tests/__mocks__/ecogesturesData.mock' describe('hash utilis test', () => { describe('hashFile test', () => { diff --git a/test/__mocks__/accountsData.mock.ts b/tests/__mocks__/accountsData.mock.ts similarity index 96% rename from test/__mocks__/accountsData.mock.ts rename to tests/__mocks__/accountsData.mock.ts index a4f24d97273ad4d134736aecdb14aa8b7f8ac637..ba83fe802f2ddcdfc4066e9150105ef33a4ddce7 100644 --- a/test/__mocks__/accountsData.mock.ts +++ b/tests/__mocks__/accountsData.mock.ts @@ -1,71 +1,71 @@ -/* eslint-disable @typescript-eslint/camelcase */ -import { Account } from 'models' - -export const accountsData: Account[] = [ - { - _id: '88e68b8450cee09fe2f077610901094d', - _rev: '1-88e68b8450cee09fe2f077610901094d', - account_type: 'enedisgrandlyon', - name: '', - oauth: { - access_token: 'MY_ACCESS_TOCKEN', - expires_at: '2020-10-09T08:00:00.285910671+02:00', - refresh_token: '', - token_type: 'Bearer', - }, - oauth_callback_results: { - issued_at: '1592232569642', - refresh_token_issued_at: '1592232569642', - scope: '/my_eneids_scope', - usage_points_id: '', - }, - cozyMetadata: { - createdAt: '2020-11-10T16:42:11.132Z', - metadataVersion: 1, - updatedAt: '2020-11-10T16:42:11.132Z', - }, - }, - { - _id: '90e68b8450cee09fe2f077610901094d', - id: '90e68b8450cee09fe2f077610901094d', - account_type: 'eglgrandlyon', - auth: { - credentials_encrypted: - 'bmFjbHI5OoL+VNCT6JDFYea1dNiBGGNJM1zY0M4uWcjhALJcQT9uk9p9WPD7+1OryCAoYf9eaSE=', - login: 'test', - }, - identifier: 'login', - state: null, - _rev: '1-90e68b8450cee09fe2f077610901094d', - _type: 'io.cozy.accounts', - cozyMetadata: { - createdAt: '2020-11-10T16:42:11.132Z', - createdByApp: 'ecolyo', - createdByAppVersion: '0.2.1', - metadataVersion: 1, - updatedAt: '2020-11-10T16:42:11.132Z', - }, - }, - { - _id: '89e68b8450cee09fe2f077610901094d', - _rev: '1-89e68b8450cee09fe2f077610901094d', - account_type: 'grdfgrandlyon', - name: '', - oauth: { - access_token: 'MY_ACCESS_TOCKEN', - expires_at: '2020-10-09T08:00:00.285910671+02:00', - refresh_token: '', - token_type: 'Bearer', - }, - oauth_callback_results: { - id_token: 'MY_ID_TOCKEN', - pce: '12345678987654', - scope: '/my_grdf_scope', - }, - cozyMetadata: { - createdAt: '2020-11-10T16:42:11.132Z', - metadataVersion: 1, - updatedAt: '2020-11-10T16:42:11.132Z', - }, - }, -] +/* eslint-disable @typescript-eslint/camelcase */ +import { Account } from 'models' + +export const accountsData: Account[] = [ + { + _id: '88e68b8450cee09fe2f077610901094d', + _rev: '1-88e68b8450cee09fe2f077610901094d', + account_type: 'enedisgrandlyon', + name: '', + oauth: { + access_token: 'MY_ACCESS_TOCKEN', + expires_at: '2020-10-09T08:00:00.285910671+02:00', + refresh_token: '', + token_type: 'Bearer', + }, + oauth_callback_results: { + issued_at: '1592232569642', + refresh_token_issued_at: '1592232569642', + scope: '/my_eneids_scope', + usage_points_id: '', + }, + cozyMetadata: { + createdAt: '2020-11-10T16:42:11.132Z', + metadataVersion: 1, + updatedAt: '2020-11-10T16:42:11.132Z', + }, + }, + { + _id: '90e68b8450cee09fe2f077610901094d', + id: '90e68b8450cee09fe2f077610901094d', + account_type: 'eglgrandlyon', + auth: { + credentials_encrypted: + 'bmFjbHI5OoL+VNCT6JDFYea1dNiBGGNJM1zY0M4uWcjhALJcQT9uk9p9WPD7+1OryCAoYf9eaSE=', + login: 'test', + }, + identifier: 'login', + state: null, + _rev: '1-90e68b8450cee09fe2f077610901094d', + _type: 'io.cozy.accounts', + cozyMetadata: { + createdAt: '2020-11-10T16:42:11.132Z', + createdByApp: 'ecolyo', + createdByAppVersion: '0.2.1', + metadataVersion: 1, + updatedAt: '2020-11-10T16:42:11.132Z', + }, + }, + { + _id: '89e68b8450cee09fe2f077610901094d', + _rev: '1-89e68b8450cee09fe2f077610901094d', + account_type: 'grdfgrandlyon', + name: '', + oauth: { + access_token: 'MY_ACCESS_TOCKEN', + expires_at: '2020-10-09T08:00:00.285910671+02:00', + refresh_token: '', + token_type: 'Bearer', + }, + oauth_callback_results: { + id_token: 'MY_ID_TOCKEN', + pce: '12345678987654', + scope: '/my_grdf_scope', + }, + cozyMetadata: { + createdAt: '2020-11-10T16:42:11.132Z', + metadataVersion: 1, + updatedAt: '2020-11-10T16:42:11.132Z', + }, + }, +] diff --git a/test/__mocks__/actionData.mock.ts b/tests/__mocks__/actionData.mock.ts similarity index 100% rename from test/__mocks__/actionData.mock.ts rename to tests/__mocks__/actionData.mock.ts diff --git a/test/__mocks__/challengeEntity.mock.ts b/tests/__mocks__/challengeEntity.mock.ts similarity index 100% rename from test/__mocks__/challengeEntity.mock.ts rename to tests/__mocks__/challengeEntity.mock.ts diff --git a/test/__mocks__/challengeStateData.mock.ts b/tests/__mocks__/challengeStateData.mock.ts similarity index 96% rename from test/__mocks__/challengeStateData.mock.ts rename to tests/__mocks__/challengeStateData.mock.ts index 4a0f99267750419bb32c183bbc955400e0897e16..1aac5497649e5a449c0da9aa87c62ba4f2ddb868 100644 --- a/test/__mocks__/challengeStateData.mock.ts +++ b/tests/__mocks__/challengeStateData.mock.ts @@ -1,14 +1,14 @@ -import { ChallengeState } from 'models' -import { userChallengeData } from './userChallengeData.mock' - -export const challengeStateData: ChallengeState = { - userChallengeList: [], - currentChallenge: null, - currentDataload: [], -} - -export const challengeStateDataFull: ChallengeState = { - userChallengeList: userChallengeData, - currentChallenge: null, - currentDataload: [], -} +import { ChallengeState } from 'models' +import { userChallengeData } from './userChallengeData.mock' + +export const challengeStateData: ChallengeState = { + userChallengeList: [], + currentChallenge: null, + currentDataload: [], +} + +export const challengeStateDataFull: ChallengeState = { + userChallengeList: userChallengeData, + currentChallenge: null, + currentDataload: [], +} diff --git a/test/__mocks__/client.ts b/tests/__mocks__/client.ts similarity index 95% rename from test/__mocks__/client.ts rename to tests/__mocks__/client.ts index e154f309e24d93ab47d59295348b9ad5602246e4..250308e4b0c4676a23b1567fd3efadad07009700 100644 --- a/test/__mocks__/client.ts +++ b/tests/__mocks__/client.ts @@ -1,19 +1,19 @@ -import { Client } from 'cozy-client' - -const mockClient = ({ - query: jest.fn(), - create: jest.fn(), - save: jest.fn(), - destroy: jest.fn(), - collection: jest.fn().mockReturnValue({ - create: jest.fn(), - }), - getStackClient: jest.fn().mockReturnValue({ - fetchJSON: jest.fn(), - }), - appMetadata: { - version: '0.0.0', - }, -} as unknown) as jest.Mocked<Client> - -export default mockClient +import { Client } from 'cozy-client' + +const mockClient = ({ + query: jest.fn(), + create: jest.fn(), + save: jest.fn(), + destroy: jest.fn(), + collection: jest.fn().mockReturnValue({ + create: jest.fn(), + }), + getStackClient: jest.fn().mockReturnValue({ + fetchJSON: jest.fn(), + }), + appMetadata: { + version: '0.0.0', + }, +} as unknown) as jest.Mocked<Client> + +export default mockClient diff --git a/test/__mocks__/cozy-client.ts b/tests/__mocks__/cozy-client.ts similarity index 95% rename from test/__mocks__/cozy-client.ts rename to tests/__mocks__/cozy-client.ts index 41b24dfb572fe1b07c576e6400ac1be07890941a..7811620344d31b8e6949efb537c7a9a4af65bd10 100644 --- a/test/__mocks__/cozy-client.ts +++ b/tests/__mocks__/cozy-client.ts @@ -1,23 +1,23 @@ -import { Q as Query, QueryDefinition } from 'cozy-client' - -export const useClient = jest.fn(() => { - return { - query: jest.fn(), - create: jest.fn(), - save: jest.fn(), - destroy: jest.fn(), - collection: jest.fn().mockReturnValue({ - create: jest.fn(), - }), - getStackClient: jest.fn().mockReturnValue({ - fetchJSON: jest.fn(), - }), - appMetadata: { - version: '0.0.0', - }, - } -}) - -export const Q = (doctype: any): QueryDefinition => { - return Query(doctype) -} +import { Q as Query, QueryDefinition } from 'cozy-client' + +export const useClient = jest.fn(() => { + return { + query: jest.fn(), + create: jest.fn(), + save: jest.fn(), + destroy: jest.fn(), + collection: jest.fn().mockReturnValue({ + create: jest.fn(), + }), + getStackClient: jest.fn().mockReturnValue({ + fetchJSON: jest.fn(), + }), + appMetadata: { + version: '0.0.0', + }, + } +}) + +export const Q = (doctype: any): QueryDefinition => { + return Query(doctype) +} diff --git a/test/__mocks__/datachartData.mock.ts b/tests/__mocks__/datachartData.mock.ts similarity index 100% rename from test/__mocks__/datachartData.mock.ts rename to tests/__mocks__/datachartData.mock.ts diff --git a/test/__mocks__/duelData.mock.ts b/tests/__mocks__/duelData.mock.ts similarity index 96% rename from test/__mocks__/duelData.mock.ts rename to tests/__mocks__/duelData.mock.ts index 161aa252eac31c5faa9e4892ce6fc900533f620f..ec44157b84358a4ba9444ebd7d4f1aef6bbc9f87 100644 --- a/test/__mocks__/duelData.mock.ts +++ b/tests/__mocks__/duelData.mock.ts @@ -1,78 +1,78 @@ -import { Duration } from 'luxon' -import { UserDuel, DuelEntity } from 'models' -import { UserDuelState } from 'enum/userDuel.enum' - -export const duelEntity: DuelEntity = { - id: 'DUEL001', - title: 'Title DUEL001', - description: - 'Je parie un ours polaire que vous ne pouvez pas consommer moins que #CONSUMPTION € en 1 semaine', - - duration: Duration.fromObject({ days: 30 }), -} - -export const allDuelEntity: DuelEntity[] = [ - { - id: 'DUEL001', - title: 'Title DUEL001', - description: 'Description DUEL001', - duration: Duration.fromObject({ days: 30 }), - }, - { - id: 'DUEL002', - title: 'Title DUEL002', - description: 'Description DUEL002', - duration: Duration.fromObject({ days: 7 }), - }, -] - -export const duelData: UserDuel = { - id: 'DUEL001', - title: 'Title DUEL001', - description: - 'Je parie un ours polaire que vous ne pouvez pas consommer moins que #CONSUMPTION € en 1 semaine', - duration: Duration.fromObject({ days: 30 }), - threshold: 0, - state: UserDuelState.LOCKED, - startDate: null, - fluidTypes: [], - userConsumption: 0, -} - -export const duelDefault: UserDuel = { - id: '', - title: '', - description: '', - duration: Duration.fromObject({ days: 0 }), - threshold: 0, - state: UserDuelState.LOCKED, - startDate: null, - fluidTypes: [], - userConsumption: 0, -} - -export const allDuelData: UserDuel[] = [ - { - id: 'DUEL001', - title: 'Title DUEL001', - description: - 'Je parie un ours polaire que vous ne pouvez pas consommer moins que #CONSUMPTION € en 1 semaine', - duration: Duration.fromObject({ days: 30 }), - threshold: 1, - state: UserDuelState.LOCKED, - startDate: null, - fluidTypes: [], - userConsumption: 0, - }, - { - id: 'DUEL002', - title: 'Title DUEL002', - description: 'Description DUEL002', - duration: Duration.fromObject({ days: 7 }), - threshold: 1, - state: UserDuelState.LOCKED, - startDate: null, - fluidTypes: [], - userConsumption: 3000, - }, -] +import { Duration } from 'luxon' +import { UserDuel, DuelEntity } from 'models' +import { UserDuelState } from 'enum/userDuel.enum' + +export const duelEntity: DuelEntity = { + id: 'DUEL001', + title: 'Title DUEL001', + description: + 'Je parie un ours polaire que vous ne pouvez pas consommer moins que #CONSUMPTION € en 1 semaine', + + duration: Duration.fromObject({ days: 30 }), +} + +export const allDuelEntity: DuelEntity[] = [ + { + id: 'DUEL001', + title: 'Title DUEL001', + description: 'Description DUEL001', + duration: Duration.fromObject({ days: 30 }), + }, + { + id: 'DUEL002', + title: 'Title DUEL002', + description: 'Description DUEL002', + duration: Duration.fromObject({ days: 7 }), + }, +] + +export const duelData: UserDuel = { + id: 'DUEL001', + title: 'Title DUEL001', + description: + 'Je parie un ours polaire que vous ne pouvez pas consommer moins que #CONSUMPTION € en 1 semaine', + duration: Duration.fromObject({ days: 30 }), + threshold: 0, + state: UserDuelState.LOCKED, + startDate: null, + fluidTypes: [], + userConsumption: 0, +} + +export const duelDefault: UserDuel = { + id: '', + title: '', + description: '', + duration: Duration.fromObject({ days: 0 }), + threshold: 0, + state: UserDuelState.LOCKED, + startDate: null, + fluidTypes: [], + userConsumption: 0, +} + +export const allDuelData: UserDuel[] = [ + { + id: 'DUEL001', + title: 'Title DUEL001', + description: + 'Je parie un ours polaire que vous ne pouvez pas consommer moins que #CONSUMPTION € en 1 semaine', + duration: Duration.fromObject({ days: 30 }), + threshold: 1, + state: UserDuelState.LOCKED, + startDate: null, + fluidTypes: [], + userConsumption: 0, + }, + { + id: 'DUEL002', + title: 'Title DUEL002', + description: 'Description DUEL002', + duration: Duration.fromObject({ days: 7 }), + threshold: 1, + state: UserDuelState.LOCKED, + startDate: null, + fluidTypes: [], + userConsumption: 3000, + }, +] diff --git a/test/__mocks__/ecogesturesData.mock.ts b/tests/__mocks__/ecogesturesData.mock.ts similarity index 100% rename from test/__mocks__/ecogesturesData.mock.ts rename to tests/__mocks__/ecogesturesData.mock.ts diff --git a/test/__mocks__/explorationData.mock.ts b/tests/__mocks__/explorationData.mock.ts similarity index 100% rename from test/__mocks__/explorationData.mock.ts rename to tests/__mocks__/explorationData.mock.ts diff --git a/test/__mocks__/fileMock.js b/tests/__mocks__/fileMock.js similarity index 94% rename from test/__mocks__/fileMock.js rename to tests/__mocks__/fileMock.js index b6e6a9b068c0ddd5bfc2898f27d20edc8b7eb76e..03ca860a9b7071f3179ac788196fc0557b6d254e 100644 --- a/test/__mocks__/fileMock.js +++ b/tests/__mocks__/fileMock.js @@ -1,3 +1,3 @@ -'use strict' - -module.exports = 'test-file-stub' +'use strict' + +module.exports = 'test-file-stub' diff --git a/test/__mocks__/fluidStatusData.mock.ts b/tests/__mocks__/fluidStatusData.mock.ts similarity index 100% rename from test/__mocks__/fluidStatusData.mock.ts rename to tests/__mocks__/fluidStatusData.mock.ts diff --git a/test/__mocks__/globalStateData.mock.ts b/tests/__mocks__/globalStateData.mock.ts similarity index 95% rename from test/__mocks__/globalStateData.mock.ts rename to tests/__mocks__/globalStateData.mock.ts index e14ffa079cbdfda76f8ba57c8c60b001f4aaeef0..8f851920a7012498ddaf264f749a15752a4c7e51 100644 --- a/test/__mocks__/globalStateData.mock.ts +++ b/tests/__mocks__/globalStateData.mock.ts @@ -1,72 +1,72 @@ -import { FluidState, FluidType } from 'enum/fluid.enum' -import { ScreenType } from 'enum/screen.enum' -import { GlobalState } from 'models' - -export const globalStateData: GlobalState = { - screenType: ScreenType.MOBILE, - challengeNotification: false, - analysisNotification: false, - fluidStatus: [ - { - fluidType: FluidType.ELECTRICITY, - status: FluidState.KONNECTOR_NOT_FOUND, - lastDataDate: null, - connection: { - shouldLaunchKonnector: false, - isUpdating: false, - konnector: null, - account: null, - trigger: null, - triggerState: null, - konnectorConfig: { - name: '', - oauth: false, - slug: '', - siteLink: '', - activation: '', - }, - }, - }, - { - fluidType: FluidType.WATER, - status: FluidState.KONNECTOR_NOT_FOUND, - lastDataDate: null, - connection: { - shouldLaunchKonnector: false, - isUpdating: false, - konnector: null, - account: null, - trigger: null, - triggerState: null, - konnectorConfig: { - name: '', - oauth: false, - slug: '', - siteLink: '', - activation: '', - }, - }, - }, - { - fluidType: FluidType.GAS, - status: FluidState.KONNECTOR_NOT_FOUND, - lastDataDate: null, - connection: { - shouldLaunchKonnector: false, - isUpdating: false, - konnector: null, - account: null, - trigger: null, - triggerState: null, - konnectorConfig: { - name: '', - oauth: false, - slug: '', - siteLink: '', - activation: '', - }, - }, - }, - ], - fluidTypes: [], -} +import { FluidState, FluidType } from 'enum/fluid.enum' +import { ScreenType } from 'enum/screen.enum' +import { GlobalState } from 'models' + +export const globalStateData: GlobalState = { + screenType: ScreenType.MOBILE, + challengeNotification: false, + analysisNotification: false, + fluidStatus: [ + { + fluidType: FluidType.ELECTRICITY, + status: FluidState.KONNECTOR_NOT_FOUND, + lastDataDate: null, + connection: { + shouldLaunchKonnector: false, + isUpdating: false, + konnector: null, + account: null, + trigger: null, + triggerState: null, + konnectorConfig: { + name: '', + oauth: false, + slug: '', + siteLink: '', + activation: '', + }, + }, + }, + { + fluidType: FluidType.WATER, + status: FluidState.KONNECTOR_NOT_FOUND, + lastDataDate: null, + connection: { + shouldLaunchKonnector: false, + isUpdating: false, + konnector: null, + account: null, + trigger: null, + triggerState: null, + konnectorConfig: { + name: '', + oauth: false, + slug: '', + siteLink: '', + activation: '', + }, + }, + }, + { + fluidType: FluidType.GAS, + status: FluidState.KONNECTOR_NOT_FOUND, + lastDataDate: null, + connection: { + shouldLaunchKonnector: false, + isUpdating: false, + konnector: null, + account: null, + trigger: null, + triggerState: null, + konnectorConfig: { + name: '', + oauth: false, + slug: '', + siteLink: '', + activation: '', + }, + }, + }, + ], + fluidTypes: [], +} diff --git a/test/__mocks__/konnectorsData.mock.ts b/tests/__mocks__/konnectorsData.mock.ts similarity index 95% rename from test/__mocks__/konnectorsData.mock.ts rename to tests/__mocks__/konnectorsData.mock.ts index d9e70b5cb87c0e0c870df11ec771db034fd187a7..b1a2498685116a6c09802648a464bba217fb34fb 100644 --- a/test/__mocks__/konnectorsData.mock.ts +++ b/tests/__mocks__/konnectorsData.mock.ts @@ -1,22 +1,22 @@ -import { Konnector } from 'models' - -export const konnectorsData: Konnector[] = [ - { - _id: 'io.cozy.konnectors/enedisgrandlyon', - name: 'Enedis', - slug: 'enedisgrandlyon', - state: 'ready', - }, - { - _id: 'io.cozy.konnectors/eglgrandlyon', - name: 'EGL', - slug: 'eglgrandlyon', - state: 'ready', - }, - { - _id: 'io.cozy.konnectors/grdfgrandlyon', - name: 'GRDF', - slug: 'grdfgrandlyon', - state: 'ready', - }, -] +import { Konnector } from 'models' + +export const konnectorsData: Konnector[] = [ + { + _id: 'io.cozy.konnectors/enedisgrandlyon', + name: 'Enedis', + slug: 'enedisgrandlyon', + state: 'ready', + }, + { + _id: 'io.cozy.konnectors/eglgrandlyon', + name: 'EGL', + slug: 'eglgrandlyon', + state: 'ready', + }, + { + _id: 'io.cozy.konnectors/grdfgrandlyon', + name: 'GRDF', + slug: 'grdfgrandlyon', + state: 'ready', + }, +] diff --git a/test/__mocks__/loadDayData.mock.ts b/tests/__mocks__/loadDayData.mock.ts similarity index 95% rename from test/__mocks__/loadDayData.mock.ts rename to tests/__mocks__/loadDayData.mock.ts index 3d669c28c38268500254e6b5cfc69bf590940da7..400062adb4f1efca1db45938c7ad4560c82939e1 100644 --- a/test/__mocks__/loadDayData.mock.ts +++ b/tests/__mocks__/loadDayData.mock.ts @@ -1,52 +1,52 @@ -import { DataloadEntity } from 'models' - -export const loadDayData: DataloadEntity[] = [ - { - id: 'bf1ce3a5774e140056714c4c200c093e', - _id: 'bf1ce3a5774e140056714c4c200c093e', - _type: 'com.grandlyon.enedis.day', - _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', - day: 1, - hour: 0, - load: 25.25, - minute: 0, - month: 11, - year: 2020, - }, - { - id: 'cf7dc6f44a19b354f99b01ba1a0b4840', - _id: 'cf7dc6f44a19b354f99b01ba1a0b4840', - _type: 'com.grandlyon.enedis.day', - _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', - day: 2, - hour: 0, - load: 20.5, - minute: 0, - month: 11, - year: 2020, - }, - { - id: 'cf7dc6f44a19b354f99b01ba1a0b4840', - _id: 'cf7dc6f44a19b354f99b01ba1a0b4840', - _type: 'com.grandlyon.enedis.day', - _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', - day: 3, - hour: 0, - load: 30.33, - minute: 0, - month: 11, - year: 2020, - }, - { - id: 'cf7dc6f44a19b354f99b01ba1a0b4840', - _id: 'cf7dc6f44a19b354f99b01ba1a0b4840', - _type: 'com.grandlyon.enedis.day', - _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', - day: 4, - hour: 0, - load: 1.22, - minute: 0, - month: 11, - year: 2020, - }, -] +import { DataloadEntity } from 'models' + +export const loadDayData: DataloadEntity[] = [ + { + id: 'bf1ce3a5774e140056714c4c200c093e', + _id: 'bf1ce3a5774e140056714c4c200c093e', + _type: 'com.grandlyon.enedis.day', + _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', + day: 1, + hour: 0, + load: 25.25, + minute: 0, + month: 11, + year: 2020, + }, + { + id: 'cf7dc6f44a19b354f99b01ba1a0b4840', + _id: 'cf7dc6f44a19b354f99b01ba1a0b4840', + _type: 'com.grandlyon.enedis.day', + _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', + day: 2, + hour: 0, + load: 20.5, + minute: 0, + month: 11, + year: 2020, + }, + { + id: 'cf7dc6f44a19b354f99b01ba1a0b4840', + _id: 'cf7dc6f44a19b354f99b01ba1a0b4840', + _type: 'com.grandlyon.enedis.day', + _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', + day: 3, + hour: 0, + load: 30.33, + minute: 0, + month: 11, + year: 2020, + }, + { + id: 'cf7dc6f44a19b354f99b01ba1a0b4840', + _id: 'cf7dc6f44a19b354f99b01ba1a0b4840', + _type: 'com.grandlyon.enedis.day', + _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', + day: 4, + hour: 0, + load: 1.22, + minute: 0, + month: 11, + year: 2020, + }, +] diff --git a/test/__mocks__/loadHourData.mock.ts b/tests/__mocks__/loadHourData.mock.ts similarity index 95% rename from test/__mocks__/loadHourData.mock.ts rename to tests/__mocks__/loadHourData.mock.ts index 68f43c0a199da2ad9998a0a19bb26152b729d146..407d36833909a00c934cd2e928e5dfd93d94f510 100644 --- a/test/__mocks__/loadHourData.mock.ts +++ b/tests/__mocks__/loadHourData.mock.ts @@ -1,64 +1,64 @@ -import { DataloadEntity } from 'models' - -export const loadHourData: DataloadEntity[] = [ - { - id: 'cf7dc6f44a19b354f99b01ba1a0b4840', - _id: 'cf7dc6f44a19b354f99b01ba1a0b4840', - _type: 'com.grandlyon.enedis.hour', - _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', - day: 2, - hour: 0, - load: 4.5, - minute: 0, - month: 11, - year: 2020, - }, - { - id: 'cf7dc6f44a19b354f99b01ba1a0b4840', - _id: 'cf7dc6f44a19b354f99b01ba1a0b4840', - _type: 'com.grandlyon.enedis.hour', - _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', - day: 2, - hour: 1, - load: 1.33, - minute: 0, - month: 11, - year: 2020, - }, - { - id: 'cf7dc6f44a19b354f99b01ba1a0b4840', - _id: 'cf7dc6f44a19b354f99b01ba1a0b4840', - _type: 'com.grandlyon.enedis.hour', - _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', - day: 2, - hour: 2, - load: 3.22, - minute: 0, - month: 11, - year: 2020, - }, - { - id: 'cf7dc6f44a19b354f99b01ba1a0b4840', - _id: 'cf7dc6f44a19b354f99b01ba1a0b4840', - _type: 'com.grandlyon.enedis.hour', - _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', - day: 2, - hour: 3, - load: 7.82, - minute: 0, - month: 11, - year: 2020, - }, - { - id: 'cf7dc6f44a19b354f99b01ba1a0b4840', - _id: 'cf7dc6f44a19b354f99b01ba1a0b4840', - _type: 'com.grandlyon.enedis.hour', - _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', - day: 2, - hour: 4, - load: 1.23, - minute: 0, - month: 11, - year: 2020, - }, -] +import { DataloadEntity } from 'models' + +export const loadHourData: DataloadEntity[] = [ + { + id: 'cf7dc6f44a19b354f99b01ba1a0b4840', + _id: 'cf7dc6f44a19b354f99b01ba1a0b4840', + _type: 'com.grandlyon.enedis.hour', + _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', + day: 2, + hour: 0, + load: 4.5, + minute: 0, + month: 11, + year: 2020, + }, + { + id: 'cf7dc6f44a19b354f99b01ba1a0b4840', + _id: 'cf7dc6f44a19b354f99b01ba1a0b4840', + _type: 'com.grandlyon.enedis.hour', + _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', + day: 2, + hour: 1, + load: 1.33, + minute: 0, + month: 11, + year: 2020, + }, + { + id: 'cf7dc6f44a19b354f99b01ba1a0b4840', + _id: 'cf7dc6f44a19b354f99b01ba1a0b4840', + _type: 'com.grandlyon.enedis.hour', + _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', + day: 2, + hour: 2, + load: 3.22, + minute: 0, + month: 11, + year: 2020, + }, + { + id: 'cf7dc6f44a19b354f99b01ba1a0b4840', + _id: 'cf7dc6f44a19b354f99b01ba1a0b4840', + _type: 'com.grandlyon.enedis.hour', + _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', + day: 2, + hour: 3, + load: 7.82, + minute: 0, + month: 11, + year: 2020, + }, + { + id: 'cf7dc6f44a19b354f99b01ba1a0b4840', + _id: 'cf7dc6f44a19b354f99b01ba1a0b4840', + _type: 'com.grandlyon.enedis.hour', + _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', + day: 2, + hour: 4, + load: 1.23, + minute: 0, + month: 11, + year: 2020, + }, +] diff --git a/test/__mocks__/loadMinuteData.mock.ts b/tests/__mocks__/loadMinuteData.mock.ts similarity index 95% rename from test/__mocks__/loadMinuteData.mock.ts rename to tests/__mocks__/loadMinuteData.mock.ts index 02dc8cdfaa2864e74cf2c8581f260c772682c7e1..b2b44b9998e0a8c12feb115d7ae9b98d5b562c4b 100644 --- a/test/__mocks__/loadMinuteData.mock.ts +++ b/tests/__mocks__/loadMinuteData.mock.ts @@ -1,76 +1,76 @@ -import { DataloadEntity } from 'models' - -export const loadMinuteData: DataloadEntity[] = [ - { - id: 'bf1ce3a5774e140056714c4c200c093e', - _id: 'bf1ce3a5774e140056714c4c200c093e', - _type: 'com.grandlyon.enedis.minute', - _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', - day: 1, - hour: 23, - load: 2.25, - minute: 30, - month: 11, - year: 2020, - }, - { - id: 'cf7dc6f44a19b354f99b01ba1a0b4840', - _id: 'cf7dc6f44a19b354f99b01ba1a0b4840', - _type: 'com.grandlyon.enedis.minute', - _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', - day: 2, - hour: 0, - load: 4.5, - minute: 0, - month: 11, - year: 2020, - }, - { - id: 'cf7dc6f44a19b354f99b01ba1a0b4840', - _id: 'cf7dc6f44a19b354f99b01ba1a0b4840', - _type: 'com.grandlyon.enedis.minute', - _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', - day: 2, - hour: 0, - load: 1.33, - minute: 30, - month: 11, - year: 2020, - }, - { - id: 'cf7dc6f44a19b354f99b01ba1a0b4840', - _id: 'cf7dc6f44a19b354f99b01ba1a0b4840', - _type: 'com.grandlyon.enedis.minute', - _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', - day: 2, - hour: 1, - load: 3.22, - minute: 0, - month: 11, - year: 2020, - }, - { - id: 'cf7dc6f44a19b354f99b01ba1a0b4840', - _id: 'cf7dc6f44a19b354f99b01ba1a0b4840', - _type: 'com.grandlyon.enedis.minute', - _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', - day: 2, - hour: 1, - load: 7.82, - minute: 30, - month: 11, - year: 2020, - }, - { - id: 'cf7dc6f44a19b354f99b01ba1a0b4840', - _id: 'cf7dc6f44a19b354f99b01ba1a0b4840', - _type: 'com.grandlyon.enedis.minute', - _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', - day: 2, - hour: 2, - load: 1.23, - minute: 0, - month: 11, - year: 2020, - }, -] +import { DataloadEntity } from 'models' + +export const loadMinuteData: DataloadEntity[] = [ + { + id: 'bf1ce3a5774e140056714c4c200c093e', + _id: 'bf1ce3a5774e140056714c4c200c093e', + _type: 'com.grandlyon.enedis.minute', + _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', + day: 1, + hour: 23, + load: 2.25, + minute: 30, + month: 11, + year: 2020, + }, + { + id: 'cf7dc6f44a19b354f99b01ba1a0b4840', + _id: 'cf7dc6f44a19b354f99b01ba1a0b4840', + _type: 'com.grandlyon.enedis.minute', + _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', + day: 2, + hour: 0, + load: 4.5, + minute: 0, + month: 11, + year: 2020, + }, + { + id: 'cf7dc6f44a19b354f99b01ba1a0b4840', + _id: 'cf7dc6f44a19b354f99b01ba1a0b4840', + _type: 'com.grandlyon.enedis.minute', + _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', + day: 2, + hour: 0, + load: 1.33, + minute: 30, + month: 11, + year: 2020, + }, + { + id: 'cf7dc6f44a19b354f99b01ba1a0b4840', + _id: 'cf7dc6f44a19b354f99b01ba1a0b4840', + _type: 'com.grandlyon.enedis.minute', + _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', + day: 2, + hour: 1, + load: 3.22, + minute: 0, + month: 11, + year: 2020, + }, + { + id: 'cf7dc6f44a19b354f99b01ba1a0b4840', + _id: 'cf7dc6f44a19b354f99b01ba1a0b4840', + _type: 'com.grandlyon.enedis.minute', + _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', + day: 2, + hour: 1, + load: 7.82, + minute: 30, + month: 11, + year: 2020, + }, + { + id: 'cf7dc6f44a19b354f99b01ba1a0b4840', + _id: 'cf7dc6f44a19b354f99b01ba1a0b4840', + _type: 'com.grandlyon.enedis.minute', + _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', + day: 2, + hour: 2, + load: 1.23, + minute: 0, + month: 11, + year: 2020, + }, +] diff --git a/test/__mocks__/loadMonthData.mock.ts b/tests/__mocks__/loadMonthData.mock.ts similarity index 95% rename from test/__mocks__/loadMonthData.mock.ts rename to tests/__mocks__/loadMonthData.mock.ts index fc869cb7eda7d64ecc2b7c75a8b9e7122f8be311..dc5854e262be2d33b5e26e3ab46ed5456ce585be 100644 --- a/test/__mocks__/loadMonthData.mock.ts +++ b/tests/__mocks__/loadMonthData.mock.ts @@ -1,40 +1,40 @@ -import { DataloadEntity } from 'models' - -export const loadMonthData: DataloadEntity[] = [ - { - id: 'bf1ce3a5774e140056714c4c200c093e', - _id: 'bf1ce3a5774e140056714c4c200c093e', - _type: 'com.grandlyon.enedis.month', - _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', - day: 1, - hour: 0, - load: 125.25, - minute: 0, - month: 9, - year: 2020, - }, - { - id: 'cf7dc6f44a19b354f99b01ba1a0b4840', - _id: 'cf7dc6f44a19b354f99b01ba1a0b4840', - _type: 'com.grandlyon.enedis.month', - _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', - day: 1, - hour: 0, - load: 220.5, - minute: 0, - month: 10, - year: 2020, - }, - { - id: 'cf7dc6f44a19b354f99b01ba1a0b4840', - _id: 'cf7dc6f44a19b354f99b01ba1a0b4840', - _type: 'com.grandlyon.enedis.month', - _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', - day: 1, - hour: 0, - load: 130.33, - minute: 0, - month: 11, - year: 2020, - }, -] +import { DataloadEntity } from 'models' + +export const loadMonthData: DataloadEntity[] = [ + { + id: 'bf1ce3a5774e140056714c4c200c093e', + _id: 'bf1ce3a5774e140056714c4c200c093e', + _type: 'com.grandlyon.enedis.month', + _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', + day: 1, + hour: 0, + load: 125.25, + minute: 0, + month: 9, + year: 2020, + }, + { + id: 'cf7dc6f44a19b354f99b01ba1a0b4840', + _id: 'cf7dc6f44a19b354f99b01ba1a0b4840', + _type: 'com.grandlyon.enedis.month', + _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', + day: 1, + hour: 0, + load: 220.5, + minute: 0, + month: 10, + year: 2020, + }, + { + id: 'cf7dc6f44a19b354f99b01ba1a0b4840', + _id: 'cf7dc6f44a19b354f99b01ba1a0b4840', + _type: 'com.grandlyon.enedis.month', + _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', + day: 1, + hour: 0, + load: 130.33, + minute: 0, + month: 11, + year: 2020, + }, +] diff --git a/test/__mocks__/loadYearData.mock.ts b/tests/__mocks__/loadYearData.mock.ts similarity index 95% rename from test/__mocks__/loadYearData.mock.ts rename to tests/__mocks__/loadYearData.mock.ts index 467b33c64452ed7bc3f74a4d986d1a94d6afb1a2..033a5c6b5c508d2f13babdb1166c7abe739f451c 100644 --- a/test/__mocks__/loadYearData.mock.ts +++ b/tests/__mocks__/loadYearData.mock.ts @@ -1,40 +1,40 @@ -import { DataloadEntity } from 'models' - -export const loadYearData: DataloadEntity[] = [ - { - id: 'bf1ce3a5774e140056714c4c200c093e', - _id: 'bf1ce3a5774e140056714c4c200c093e', - _type: 'com.grandlyon.enedis.year', - _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', - day: 1, - hour: 0, - load: 125.25, - minute: 0, - month: 1, - year: 2018, - }, - { - id: 'cf7dc6f44a19b354f99b01ba1a0b4840', - _id: 'cf7dc6f44a19b354f99b01ba1a0b4840', - _type: 'com.grandlyon.enedis.year', - _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', - day: 0, - hour: 0, - load: 220.5, - minute: 0, - month: 0, - year: 2019, - }, - { - id: 'cf7dc6f44a19b354f99b01ba1a0b4840', - _id: 'cf7dc6f44a19b354f99b01ba1a0b4840', - _type: 'com.grandlyon.enedis.year', - _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', - day: 1, - hour: 0, - load: 130.33, - minute: 0, - month: 1, - year: 2020, - }, -] +import { DataloadEntity } from 'models' + +export const loadYearData: DataloadEntity[] = [ + { + id: 'bf1ce3a5774e140056714c4c200c093e', + _id: 'bf1ce3a5774e140056714c4c200c093e', + _type: 'com.grandlyon.enedis.year', + _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', + day: 1, + hour: 0, + load: 125.25, + minute: 0, + month: 1, + year: 2018, + }, + { + id: 'cf7dc6f44a19b354f99b01ba1a0b4840', + _id: 'cf7dc6f44a19b354f99b01ba1a0b4840', + _type: 'com.grandlyon.enedis.year', + _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', + day: 0, + hour: 0, + load: 220.5, + minute: 0, + month: 0, + year: 2019, + }, + { + id: 'cf7dc6f44a19b354f99b01ba1a0b4840', + _id: 'cf7dc6f44a19b354f99b01ba1a0b4840', + _type: 'com.grandlyon.enedis.year', + _rev: '1-4fe971dff073a3c3c6cc12a0246e642e', + day: 1, + hour: 0, + load: 130.33, + minute: 0, + month: 1, + year: 2020, + }, +] diff --git a/test/__mocks__/modalStateData.mock.ts b/tests/__mocks__/modalStateData.mock.ts similarity index 95% rename from test/__mocks__/modalStateData.mock.ts rename to tests/__mocks__/modalStateData.mock.ts index 48e768250888427377c28556425d7a26016f65b8..b8543efe8952c02cf00c34420c88eb2c684d3a4e 100644 --- a/test/__mocks__/modalStateData.mock.ts +++ b/tests/__mocks__/modalStateData.mock.ts @@ -1,5 +1,5 @@ -import { ModalState } from 'models' - -export const modalStateData: ModalState = { - isFeedbacksOpen: false, -} +import { ModalState } from 'models' + +export const modalStateData: ModalState = { + isFeedbacksOpen: false, +} diff --git a/test/__mocks__/profile.mock.ts b/tests/__mocks__/profile.mock.ts similarity index 97% rename from test/__mocks__/profile.mock.ts rename to tests/__mocks__/profile.mock.ts index 055c249cf353369b9a52ad737c16d68bafb196cb..543663b7f29e819b3147e5c4a1a41aa0fbb67311 100644 --- a/test/__mocks__/profile.mock.ts +++ b/tests/__mocks__/profile.mock.ts @@ -1,52 +1,52 @@ -import { FluidType } from 'enum/fluid.enum' -import { - ConstructionYear, - Floor, - IndividualOrCollective, - HotWaterEquipment, - HousingType, - OutsideFacingWalls, - ThreeChoicesAnswer, -} from 'enum/profileType.enum' -import { DateTime } from 'luxon' -import { Profile } from 'models' - -export const profileData: Profile = { - _id: '4d9403218ef13e65b2e3a8ad1700bc41', - _rev: '16-57473da4fc26315247c217083175dfa0', - id: '4d9403218ef13e65b2e3a8ad1700bc41', - ecogestureHash: '9798a0aaccb47cff906fc4931a2eff5f9371dd8b', - challengeHash: '1136feb6185c7643e071d14180c0e95782aa4ba3', - duelHash: '1136feb6185c7643e071d14180c0e95782aa4ba3', - quizHash: '1136feb6185c7643e071d14180c0e95782aa4ba3', - explorationHash: '1136feb6185c7643e071d14180c0e95782aa4ba3', - isFirstConnection: true, - lastConnectionDate: DateTime.fromISO('2020-11-03T00:00:00.000Z', { - zone: 'utc', - }), - haveSeenOldFluidModal: false, - haveSeenLastAnalysis: true, - monthlyAnalysisDate: DateTime.fromISO('2020-11-03T00:00:00.000Z', { - zone: 'utc', - }), - sendAnalysisNotification: false, - profileType: { - housingType: HousingType.APPARTMENT, - constructionYear: ConstructionYear.AFTER_1999, - area: 35, - occupantsNumber: 1, - outsideFacingWalls: OutsideFacingWalls.ONE, - floor: Floor.INTERMEDIATE_FLOOR, - heating: IndividualOrCollective.COLLECTIVE, - coldWater: IndividualOrCollective.INDIVIDUAL, - hotWater: IndividualOrCollective.INDIVIDUAL, - individualInsulationWork: [], - hasInstalledVentilation: ThreeChoicesAnswer.NO, - hasReplacedHeater: ThreeChoicesAnswer.NO, - hotWaterEquipment: HotWaterEquipment.OTHER, - warmingFluid: FluidType.ELECTRICITY, - hotWaterFluid: FluidType.ELECTRICITY, - cookingFluid: FluidType.GAS, - }, - isProfileTypeCompleted: false, -} +import { FluidType } from 'enum/fluid.enum' +import { + ConstructionYear, + Floor, + IndividualOrCollective, + HotWaterEquipment, + HousingType, + OutsideFacingWalls, + ThreeChoicesAnswer, +} from 'enum/profileType.enum' +import { DateTime } from 'luxon' +import { Profile } from 'models' + +export const profileData: Profile = { + _id: '4d9403218ef13e65b2e3a8ad1700bc41', + _rev: '16-57473da4fc26315247c217083175dfa0', + id: '4d9403218ef13e65b2e3a8ad1700bc41', + ecogestureHash: '9798a0aaccb47cff906fc4931a2eff5f9371dd8b', + challengeHash: '1136feb6185c7643e071d14180c0e95782aa4ba3', + duelHash: '1136feb6185c7643e071d14180c0e95782aa4ba3', + quizHash: '1136feb6185c7643e071d14180c0e95782aa4ba3', + explorationHash: '1136feb6185c7643e071d14180c0e95782aa4ba3', + isFirstConnection: true, + lastConnectionDate: DateTime.fromISO('2020-11-03T00:00:00.000Z', { + zone: 'utc', + }), + haveSeenOldFluidModal: false, + haveSeenLastAnalysis: true, + monthlyAnalysisDate: DateTime.fromISO('2020-11-03T00:00:00.000Z', { + zone: 'utc', + }), + sendAnalysisNotification: false, + profileType: { + housingType: HousingType.APPARTMENT, + constructionYear: ConstructionYear.AFTER_1999, + area: 35, + occupantsNumber: 1, + outsideFacingWalls: OutsideFacingWalls.ONE, + floor: Floor.INTERMEDIATE_FLOOR, + heating: IndividualOrCollective.COLLECTIVE, + coldWater: IndividualOrCollective.INDIVIDUAL, + hotWater: IndividualOrCollective.INDIVIDUAL, + individualInsulationWork: [], + hasInstalledVentilation: ThreeChoicesAnswer.NO, + hasReplacedHeater: ThreeChoicesAnswer.NO, + hotWaterEquipment: HotWaterEquipment.OTHER, + warmingFluid: FluidType.ELECTRICITY, + hotWaterFluid: FluidType.ELECTRICITY, + cookingFluid: FluidType.GAS, + }, + isProfileTypeCompleted: false, +} diff --git a/test/__mocks__/profileType.mock.ts b/tests/__mocks__/profileType.mock.ts similarity index 100% rename from test/__mocks__/profileType.mock.ts rename to tests/__mocks__/profileType.mock.ts diff --git a/test/__mocks__/quizData.mock.ts b/tests/__mocks__/quizData.mock.ts similarity index 100% rename from test/__mocks__/quizData.mock.ts rename to tests/__mocks__/quizData.mock.ts diff --git a/test/__mocks__/store.ts b/tests/__mocks__/store.ts similarity index 100% rename from test/__mocks__/store.ts rename to tests/__mocks__/store.ts diff --git a/test/__mocks__/triggerStateData.mock.ts b/tests/__mocks__/triggerStateData.mock.ts similarity index 97% rename from test/__mocks__/triggerStateData.mock.ts rename to tests/__mocks__/triggerStateData.mock.ts index f921419f45ffe068bc02216f477b242971fe6bcd..cb7db8fd0f7ef966313941d513a694a2a141d51c 100644 --- a/test/__mocks__/triggerStateData.mock.ts +++ b/tests/__mocks__/triggerStateData.mock.ts @@ -1,14 +1,14 @@ -/* eslint-disable @typescript-eslint/camelcase */ -import { TriggerState } from 'models' - -export const triggerStateData: TriggerState = { - trigger_id: '238ba37b8bc8130bd323edb5c1005c8f', - status: 'errored', - last_execution: '2020-11-13T10:03:16.4121536Z', - last_executed_job_id: '238ba37b8bc8130bd323edb5c1006b56', - last_failure: '2020-11-13T10:03:16.4121536Z', - last_failed_job_id: '238ba37b8bc8130bd323edb5c1006b56', - last_error: 'fork/exec : no such file or directory', - last_manual_execution: '2020-11-13T10:03:16.4121536Z', - last_manual_job_id: '238ba37b8bc8130bd323edb5c1006b56', -} +/* eslint-disable @typescript-eslint/camelcase */ +import { TriggerState } from 'models' + +export const triggerStateData: TriggerState = { + trigger_id: '238ba37b8bc8130bd323edb5c1005c8f', + status: 'errored', + last_execution: '2020-11-13T10:03:16.4121536Z', + last_executed_job_id: '238ba37b8bc8130bd323edb5c1006b56', + last_failure: '2020-11-13T10:03:16.4121536Z', + last_failed_job_id: '238ba37b8bc8130bd323edb5c1006b56', + last_error: 'fork/exec : no such file or directory', + last_manual_execution: '2020-11-13T10:03:16.4121536Z', + last_manual_job_id: '238ba37b8bc8130bd323edb5c1006b56', +} diff --git a/test/__mocks__/triggersData.mock.ts b/tests/__mocks__/triggersData.mock.ts similarity index 96% rename from test/__mocks__/triggersData.mock.ts rename to tests/__mocks__/triggersData.mock.ts index 76dbb299a133d110e7f1eee74a341d79193a2b80..698c303a838d90d0063187419eb9c1f72e428739 100644 --- a/test/__mocks__/triggersData.mock.ts +++ b/tests/__mocks__/triggersData.mock.ts @@ -1,67 +1,67 @@ -import { Trigger } from 'models' - -export const triggersData: Trigger[] = [ - { - _id: '3ed832cec67e6e0b2c6382edd30df11c', - domain: 'cozy.tools:8080', - prefix: 'cozy35ba44d2d1749e6f21646edce51e7190', - type: '@cron', - worker: 'konnector', - arguments: '0 47 8 * * *', - debounce: '', - options: null, - message: { - account: '88e68b8450cee09fe2f077610901094d', - konnector: 'enedisgrandlyon', - }, - cozyMetadata: { - doctypeVersion: '1', - metadataVersion: 1, - createdAt: '2020-10-09T08:00:00.6092798Z', - createdByApp: 'ecolyo', - updatedAt: '2020-10-09T08:00:00.6092798Z', - }, - }, - { - _id: '5ed832cec67e6e0b2c6382edd30df11c', - domain: 'cozy.tools:8080', - prefix: 'cozy35ba44d2d1749e6f21646edce51e7190', - type: '@cron', - worker: 'konnector', - arguments: '0 47 8 * * *', - debounce: '', - options: null, - message: { - account: '90e68b8450cee09fe2f077610901094d', - konnector: 'eglgrandlyon', - }, - cozyMetadata: { - doctypeVersion: '1', - metadataVersion: 1, - createdAt: '2020-10-09T08:00:00.6092798Z', - createdByApp: 'ecolyo', - updatedAt: '2020-10-09T08:00:00.6092798Z', - }, - }, - { - _id: '4ed832cec67e6e0b2c6382edd30df11c', - domain: 'cozy.tools:8080', - prefix: 'cozy35ba44d2d1749e6f21646edce51e7190', - type: '@cron', - worker: 'konnector', - arguments: '0 47 8 * * *', - debounce: '', - options: null, - message: { - account: '89e68b8450cee09fe2f077610901094d', - konnector: 'grdfgrandlyon', - }, - cozyMetadata: { - doctypeVersion: '1', - metadataVersion: 1, - createdAt: '2020-10-09T08:00:00.6092798Z', - createdByApp: 'ecolyo', - updatedAt: '2020-10-09T08:00:00.6092798Z', - }, - }, -] +import { Trigger } from 'models' + +export const triggersData: Trigger[] = [ + { + _id: '3ed832cec67e6e0b2c6382edd30df11c', + domain: 'cozy.tools:8080', + prefix: 'cozy35ba44d2d1749e6f21646edce51e7190', + type: '@cron', + worker: 'konnector', + arguments: '0 47 8 * * *', + debounce: '', + options: null, + message: { + account: '88e68b8450cee09fe2f077610901094d', + konnector: 'enedisgrandlyon', + }, + cozyMetadata: { + doctypeVersion: '1', + metadataVersion: 1, + createdAt: '2020-10-09T08:00:00.6092798Z', + createdByApp: 'ecolyo', + updatedAt: '2020-10-09T08:00:00.6092798Z', + }, + }, + { + _id: '5ed832cec67e6e0b2c6382edd30df11c', + domain: 'cozy.tools:8080', + prefix: 'cozy35ba44d2d1749e6f21646edce51e7190', + type: '@cron', + worker: 'konnector', + arguments: '0 47 8 * * *', + debounce: '', + options: null, + message: { + account: '90e68b8450cee09fe2f077610901094d', + konnector: 'eglgrandlyon', + }, + cozyMetadata: { + doctypeVersion: '1', + metadataVersion: 1, + createdAt: '2020-10-09T08:00:00.6092798Z', + createdByApp: 'ecolyo', + updatedAt: '2020-10-09T08:00:00.6092798Z', + }, + }, + { + _id: '4ed832cec67e6e0b2c6382edd30df11c', + domain: 'cozy.tools:8080', + prefix: 'cozy35ba44d2d1749e6f21646edce51e7190', + type: '@cron', + worker: 'konnector', + arguments: '0 47 8 * * *', + debounce: '', + options: null, + message: { + account: '89e68b8450cee09fe2f077610901094d', + konnector: 'grdfgrandlyon', + }, + cozyMetadata: { + doctypeVersion: '1', + metadataVersion: 1, + createdAt: '2020-10-09T08:00:00.6092798Z', + createdByApp: 'ecolyo', + updatedAt: '2020-10-09T08:00:00.6092798Z', + }, + }, +] diff --git a/test/__mocks__/userChallengeData.mock.ts b/tests/__mocks__/userChallengeData.mock.ts similarity index 100% rename from test/__mocks__/userChallengeData.mock.ts rename to tests/__mocks__/userChallengeData.mock.ts diff --git a/test/jestLib/setup.js b/tests/jestLib/setup.js similarity index 95% rename from test/jestLib/setup.js rename to tests/jestLib/setup.js index 918766e8e218532d5b58406bcee4cc6b8241eeb8..46f8d0d2523f3d6a709e375759f70074a9fd8d85 100644 --- a/test/jestLib/setup.js +++ b/tests/jestLib/setup.js @@ -1,37 +1,37 @@ -require('babel-polyfill') -require('jest-canvas-mock') - -import { configure } from 'enzyme' -import Adapter from 'enzyme-adapter-react-16' - -configure({ adapter: new Adapter() }) - -// polyfill for requestAnimationFrame -/* istanbul ignore next */ -global.requestAnimationFrame = cb => { - setTimeout(cb, 0) -} - -global.cozy = { - bar: { - BarLeft: ({ children }) => children, - BarRight: ({ children }) => children, - BarCenter: ({ children }) => children, - setTheme: () => null, - }, -} - -Object.defineProperty(window, 'getComputedStyle', { - value: () => ({ - getPropertyValue: prop => { - switch (prop) { - case '--blue': - return '#58ffff' - case '--greyDark': - return '#7b7b7b' - default: - return '#FFFFFF' - } - }, - }), -}) +require('babel-polyfill') +require('jest-canvas-mock') + +import { configure } from 'enzyme' +import Adapter from 'enzyme-adapter-react-16' + +configure({ adapter: new Adapter() }) + +// polyfill for requestAnimationFrame +/* istanbul ignore next */ +global.requestAnimationFrame = cb => { + setTimeout(cb, 0) +} + +global.cozy = { + bar: { + BarLeft: ({ children }) => children, + BarRight: ({ children }) => children, + BarCenter: ({ children }) => children, + setTheme: () => null, + }, +} + +Object.defineProperty(window, 'getComputedStyle', { + value: () => ({ + getPropertyValue: prop => { + switch (prop) { + case '--blue': + return '#58ffff' + case '--greyDark': + return '#7b7b7b' + default: + return '#FFFFFF' + } + }, + }), +}) diff --git a/test/lib/I18n.js b/tests/lib/I18n.js similarity index 95% rename from test/lib/I18n.js rename to tests/lib/I18n.js index 5f2adf75cb2daaed03d7e22dd3e827ade5f9b0a9..1e6e9d09810c76df4792717f09e17f53d3e1fc12 100644 --- a/test/lib/I18n.js +++ b/tests/lib/I18n.js @@ -1,12 +1,12 @@ -'use strict' - -import { I18n } from 'cozy-ui/react/I18n' - -const I18nComponent = new I18n({ - lang: 'en', - dictRequire: lang => require(`../../src/locales/${lang}`), -}) - -export const mockT = I18nComponent.getChildContext().t - -export const mockF = I18nComponent.getChildContext().f +'use strict' + +import { I18n } from 'cozy-ui/react/I18n' + +const I18nComponent = new I18n({ + lang: 'en', + dictRequire: lang => require(`../../src/locales/${lang}`), +}) + +export const mockT = I18nComponent.getChildContext().t + +export const mockF = I18nComponent.getChildContext().f diff --git a/tsconfig.json b/tsconfig.json index e35a29797c481d1dcb9c165f4c85d81c4b1bd5f3..037d4ebe9ccd92b00da869121ad3e3cb1e7bb416 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,25 +1,32 @@ -{ - "compilerOptions": { - "target": "esnext", - "baseUrl": "src", - "allowJs": true, - "skipLibCheck": true, - "esModuleInterop": true, - "allowSyntheticDefaultImports": true, - "strict": true, - "forceConsistentCasingInFileNames": true, - "module": "esnext", - "moduleResolution": "node", - "resolveJsonModule": true, - "isolatedModules": true, - "noEmit": true, - "jsx": "react", - "lib": [ - "es6", - "dom" - ] - }, - "include": [ - "src/**/*", "test/**/*" - ] -} +{ + "compilerOptions": { + "target": "esnext", + "baseUrl": "src", + "allowJs": true, + "skipLibCheck": true, + "esModuleInterop": true, + "allowSyntheticDefaultImports": true, + "strict": true, + "forceConsistentCasingInFileNames": true, + "module": "esnext", + "moduleResolution": "node", + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": true, + "jsx": "react", + "lib": [ + "esnext", + "dom" + ], + "paths": { + "*": [ + "*", + "../node_modules/*", + "types/*" + ] + } + }, + "include": [ + "src/**/*", "tests/**/*" + ] +}