Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

chore(Bonus Pagamenti Digitali): [#175636284] Add tests for bpdsummarycomponent & bpdAllPeriodsWithAmountSelector #2352

Merged
merged 9 commits into from
Nov 11, 2020

Conversation

fabriziofff
Copy link
Contributor

Short description

This pr adds some test for BPDSummaryComponent and bpdAllPeriodsWithAmountSelector.

How to test

  • Run ts/features/bonus/bpd/screens/details/components/summary/__test__/bpdSummaryComponent.test.tsx
  • Run ts/features/bonus/bpd/store/reducers/details/__test__/combiner.test.ts

@pagopa-github-bot pagopa-github-bot changed the title [#175636284] Add tests for bpdsummarycomponent & bpdAllPeriodsWithAmountSelector chore(Bonus Pagamenti Digitali): [#175636284] Add tests for bpdsummarycomponent & bpdAllPeriodsWithAmountSelector Nov 9, 2020
@pagopa-github-bot
Copy link
Collaborator

pagopa-github-bot commented Nov 9, 2020

Affected stories

  • ⚙️ #175636284: Come DEV voglio testare il componente BpdSummaryComponent

New dependencies added: @testing-library/jest-native, @testing-library/react-native, @types/redux-mock-store, mockdate and redux-mock-store.

@testing-library/jest-native

Author: Brandon Carroll

Description: Custom jest matchers to test the state of React Native

Homepage: https://github.com/testing-library/jest-native#readme

Createdover 1 year ago
Last Updatedabout 1 month ago
LicenseMIT
Maintainers16
Releases12
Direct Dependencieschalk, jest-diff, jest-matcher-utils, ramda, pretty-format and redent
Keywordstesting, testing-library, jest and react-native
This README is too long to show.

@testing-library/react-native

Author: Michał Pierzchała

Description: Simple and complete React Native testing utilities that encourage good testing practices.

Homepage: https://callstack.github.io/react-native-testing-library

Createdover 1 year ago
Last Updated21 days ago
LicenseMIT
Maintainers16
Releases27
Direct Dependenciespretty-format
Keywordsreact-native, react, test and integration
README

React Native Testing Library

owl

Simple and complete React Native testing utilities that encourage good testing practices.

Version
PRs Welcome
Chat
Sponsored by Callstack

We renamed the react-native-testing-library npm package to @testing-library/react-native, officially joining the "Testing Library" family 🎉. Read the migration guide.

The problem

You want to write maintainable tests for your React Native components. As a part of this goal, you want your tests to avoid including implementation details of your components and rather focus on making your tests give you the confidence for which they are intended. As part of this, you want your testbase to be maintainable in the long run so refactors of your components (changes to implementation but not functionality) don't break your tests and slow you and your team down.

This solution

The React Native Testing Library (RNTL) is a lightweight solution for testing React Native components. It provides light utility functions on top of react-test-renderer, in a way that encourages better testing practices. Its primary guiding principle is:

The more your tests resemble the way your software is used, the more confidence they can give you.

This project is inspired by React Testing Library. Tested to work with Jest, but it should work with other test runners as well.

Installation

Open a Terminal in your project's folder and run:

Using yarn

yarn add --dev @testing-library/react-native

Using npm

npm install --save-dev @testing-library/react-native

This library has a peerDependencies listing for react-test-renderer and, of course, react. Make sure to install them too!

In order to properly use helpers for async tests (findBy queries and waitFor) you need at least React >=16.9.0 (featuring async act) or React Native >=0.60 (which comes with React >=16.9.0).

Additional Jest matchers

In order to use additional React Native-specific jest matchers from @testing-library/jest-native package add it to your project:

Using yarn

yarn add --dev @testing-library/jest-native

Using npm

npm install --save-dev @testing-library/jest-native

Then automatically add it to your jest tests by using setupFilesAfterEnv option in your Jest configuration (it's usually located either in package.json under "jest" key or in a jest.config.js file):

{
  "preset": "react-native",
  "setupFilesAfterEnv": ["@testing-library/jest-native/extend-expect"]
}

Flow

Note for Flow users – you'll also need to install typings for react-test-renderer:

flow-typed install react-test-renderer

Example

import { render, fireEvent } from '@testing-library/react-native';
import { QuestionsBoard } from '../QuestionsBoard';

test('form submits two answers', () => {
  const allQuestions = ['q1', 'q2'];
  const mockFn = jest.fn();

  const { getAllByA11yLabel, getByText } = render(
    <QuestionsBoard questions={allQuestions} onSubmit={mockFn} />
  );

  const answerInputs = getAllByA11yLabel('answer input');

  fireEvent.changeText(answerInputs[0], 'a1');
  fireEvent.changeText(answerInputs[1], 'a2');
  fireEvent.press(getByText('Submit'));

  expect(mockFn).toBeCalledWith({
    '1': { q: 'q1', a: 'a1' },
    '2': { q: 'q2', a: 'a2' },
  });
});

You can find the source of QuestionsBoard component and this example here.

API / Usage

The public API of @testing-library/react-native is focused around these essential methods:

  • render – deeply renders given React element and returns helpers to query the output components.
  • fireEvent - invokes named event handler on the element.
  • waitFor - waits for non-deterministic periods of time until queried element is added or times out.
  • waitForElementToBeRemoved - waits for non-deterministic periods of time until queried element is removed or times out.
  • within - creates a queries object scoped for given element.

Migration Guides

Related External Resources

Made with ❤️ at Callstack

React Native Testing Library is an open source project and will always remain free to use. If you think it's cool, please star it 🌟. Callstack is a group of React and React Native geeks, contact us at hello@callstack.com if you need any help with these or just want to say hi!


Supported and used by Rally Health.

@types/redux-mock-store

Author: Unknown

Description: TypeScript definitions for Redux Mock Store

Homepage: http://npmjs.com/package/@types/redux-mock-store

Createdover 4 years ago
Last Updatedabout 13 hours ago
LicenseMIT
Maintainers1
Releases17
Direct Dependenciesredux
README

Installation

npm install --save @types/redux-mock-store

Summary

This package contains type definitions for Redux Mock Store (https://github.com/dmitry-zaets/redux-mock-store).

Details

Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/redux-mock-store.

Additional Details

  • Last updated: Mon, 27 Jan 2020 22:31:33 GMT
  • Dependencies: @types/redux
  • Global values: none

Credits

These definitions were written by Marian Palkus (https://github.com/MarianPalkus), and Cap3 (http://www.cap3.de).

mockdate

Author: Bob Lauer

Description: A JavaScript mock Date object that can be used to change when "now" is.

Homepage: https://github.com/boblauer/MockDate

Createdover 6 years ago
Last Updated6 months ago
LicenseMIT
Maintainers1
Releases16
Direct Dependencies
Keywordsdate, mock and test
README

MockDate

A JavaScript Mock Date object that can be used to change when "now" is.

Build Status

Installation

npm install mockdate

Environment Support

MockDate has been tested in Node, IE9+, Chrome, Firefox, and Opera.

Usage

import MockDate from 'mockdate'

API

MockDate.set(date)

date

date: Object

The Date to be returned when no parameters are passed to new Date(). Supports any object that has a .valueOf method that returns a value that can be passed to new Date().

date: String

The string representation of the date which is passed to the new Date() constructor. This creates the Date to be returned when no parameters are passed to new Date().

date: Number

The millisecond representation of the Date to be returned when no parameters are passed to new Date().

MockDate.reset();

Will restore the original Date object back to the native implementation.

Example

MockDate.set('2000-11-22');

new Date().toString() // "Tue Nov 21 2000 18:00:00 GMT-0600 (CST)"

MockDate.set('1/30/2000');

new Date().toString() // "Sun Jan 30 2000 00:00:00 GMT-0600 (CST)"

MockDate.set(new Date('2/20/2000'));

new Date().toString() // "Sun Feb 20 2000 00:00:00 GMT-0600 (CST)"

MockDate.set(moment('3/30/2000').toDate()); // using momentjs

new Date().toString() // "Thu Mar 30 2000 00:00:00 GMT-0600 (CST)"

MockDate.reset();

new Date().toString() // "Mon Mar 17 2014 18:08:44 GMT-0500 (CDT)"

Test

npm test

redux-mock-store

Author: Arnaud Benard

Description: A mock store for testing your redux async action creators and middleware

Homepage: https://github.com/arnaudbenard/redux-mock-store#readme

Createdabout 5 years ago
Last Updated11 months ago
LicenseMIT
Maintainers2
Releases26
Direct Dependencieslodash.isplainobject
README

redux-mock-store Circle CI

npm

A mock store for testing Redux async action creators and middleware. The mock store will create an array of dispatched actions which serve as an action log for tests.

Please note that this library is designed to test the action-related logic, not the reducer-related one. In other words, it does not update the Redux store. If you want a complex test combining actions and reducers together, take a look at other libraries (e.g., redux-actions-assertions). Refer to issue #71 for more details.

Install

npm install redux-mock-store --save-dev

Or

yarn add redux-mock-store --dev

Usage

Synchronous actions

The simplest usecase is for synchronous actions. In this example, we will test if the addTodo action returns the right payload. redux-mock-store saves all the dispatched actions inside the store instance. You can get all the actions by calling store.getActions(). Finally, you can use any assertion library to test the payload.

import configureStore from 'redux-mock-store' //ES6 modules
const { configureStore } = require('redux-mock-store') //CommonJS

const middlewares = []
const mockStore = configureStore(middlewares)

// You would import the action from your codebase in a real scenario
const addTodo = () => ({ type: 'ADD_TODO' })

it('should dispatch action', () => {

  // Initialize mockstore with empty state
  const initialState = {}
  const store = mockStore(initialState)

  // Dispatch the action
  store.dispatch(addTodo())

  // Test if your store dispatched the expected actions
  const actions = store.getActions()
  const expectedPayload = { type: 'ADD_TODO' }
  expect(actions).toEqual([expectedPayload])
})

Asynchronous actions

A common usecase for an asynchronous action is a HTTP request to a server. In order to test those types of actions, you will need to call store.getActions() at the end of the request.

import configureStore from 'redux-mock-store'
import thunk from 'redux-thunk'

const middlewares = [thunk] // add your middlewares like `redux-thunk`
const mockStore = configureStore(middlewares)

// You would import the action from your codebase in a real scenario
function success() {
  return {
    type: 'FETCH_DATA_SUCCESS'
  }
}

function fetchData () {
  return dispatch => {
    return fetch('/users.json') // Some async action with promise
      .then(() => dispatch(success()))
  };
}

it('should execute fetch data', () => {
  const store = mockStore({})

  // Return the promise
  return store.dispatch(fetchData())
    .then(() => {
      const actions = store.getActions()
      expect(actions[0]).toEqual(success())
    })
})

API

configureStore(middlewares?: Array) => mockStore: Function

Configure mock store by applying the middlewares.

mockStore(getState?: Object,Function) => store: Function

Returns an instance of the configured mock store. If you want to reset your store after every test, you should call this function.

store.dispatch(action) => action

Dispatches an action through the mock store. The action will be stored in an array inside the instance and executed.

store.getState() => state: Object

Returns the state of the mock store.

store.getActions() => actions: Array

Returns the actions of the mock store.

store.clearActions()

Clears the stored actions.

store.subscribe(callback: Function) => unsubscribe: Function

Subscribe to the store.

store.replaceReducer(nextReducer: Function)

Follows the Redux API.

Old version (< 1.x.x)

https://github.com/arnaudbenard/redux-mock-store/blob/v0.0.6/README.md

License

The MIT License

Generated by 🚫 dangerJS against bf5b856

@codecov-io
Copy link

codecov-io commented Nov 10, 2020

Codecov Report

Merging #2352 (8151c32) into master (878f7df) will increase coverage by 0.38%.
The diff coverage is 100.00%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #2352      +/-   ##
==========================================
+ Coverage   48.84%   49.22%   +0.38%     
==========================================
  Files         631      633       +2     
  Lines       17714    17721       +7     
  Branches     3490     3490              
==========================================
+ Hits         8652     8724      +72     
+ Misses       9020     8954      -66     
- Partials       42       43       +1     
Impacted Files Coverage Δ
...details/components/summary/BpdSummaryComponent.tsx 73.07% <ø> (+15.38%) ⬆️
...eens/details/components/summary/TextualSummary.tsx 100.00% <ø> (+62.50%) ⬆️
...omponents/summary/TransactionsGraphicalSummary.tsx 100.00% <ø> (+31.57%) ⬆️
...ns/details/components/summary/base/ProgressBar.tsx 100.00% <ø> (+22.22%) ⬆️
...atures/bonus/bpd/store/reducers/__mock__/amount.ts 100.00% <100.00%> (ø)
...tures/bonus/bpd/store/reducers/__mock__/periods.ts 100.00% <100.00%> (ø)
ts/store/reducers/profile.ts 44.59% <0.00%> (+1.35%) ⬆️
ts/utils/accessibility.ts 37.50% <0.00%> (+3.12%) ⬆️
... and 11 more

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 878f7df...8151c32. Read the comment docs.

@Undermaken Undermaken merged commit b38b2fc into master Nov 11, 2020
@Undermaken Undermaken deleted the 175636284-test-bpdsummarycomponent branch November 11, 2020 15:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants