Unverified Commit b3ed6288 authored by Tamika Tannis's avatar Tamika Tannis Committed by GitHub

Test Improvements: Date() issues, ReactRouterProps, & updated doc (#217)

* Test improvements

* Remove unnecessary import

* Cleanup
parent aad12eda
...@@ -8,31 +8,17 @@ import SearchBar from 'components/SearchPage/SearchBar'; ...@@ -8,31 +8,17 @@ import SearchBar from 'components/SearchPage/SearchBar';
import MyBookmarks from 'components/common/Bookmark/MyBookmarks'; import MyBookmarks from 'components/common/Bookmark/MyBookmarks';
import PopularTables from 'components/common/PopularTables'; import PopularTables from 'components/common/PopularTables';
import { getMockRouterProps } from 'fixtures/mockRouter';
describe('HomePage', () => { describe('HomePage', () => {
const setup = (propOverrides?: Partial<HomePageProps>) => { const setup = (propOverrides?: Partial<HomePageProps>) => {
const mockLocation = {
search: '/search?searchTerm=testName&selectedTab=table&pageIndex=1',
};
const routerProps = getMockRouterProps<any>(null, mockLocation);
const props: HomePageProps = { const props: HomePageProps = {
searchReset: jest.fn(), searchReset: jest.fn(),
history: { ...routerProps,
length: 2,
action: "POP",
location: jest.fn() as any,
push: jest.fn(),
replace: jest.fn(),
go: jest.fn(),
goBack: jest.fn(),
goForward: jest.fn(),
block: jest.fn(),
createHref: jest.fn(),
listen: jest.fn(),
},
location: {
search: '/search?searchTerm=testName&selectedTab=table&pageIndex=1',
pathname: 'mockstr',
state: jest.fn(),
hash: 'mockstr',
},
match: jest.fn() as any,
staticContext: jest.fn() as any,
...propOverrides ...propOverrides
}; };
const wrapper = shallow<HomePage>(<HomePage {...props} />) const wrapper = shallow<HomePage>(<HomePage {...props} />)
......
...@@ -45,7 +45,7 @@ interface DispatchFromProps { ...@@ -45,7 +45,7 @@ interface DispatchFromProps {
getBookmarksForUser: (userId: string) => GetBookmarksForUserRequest; getBookmarksForUser: (userId: string) => GetBookmarksForUserRequest;
} }
interface RouteProps { export interface RouteProps {
userId: string; userId: string;
} }
......
...@@ -7,9 +7,10 @@ import { shallow } from 'enzyme'; ...@@ -7,9 +7,10 @@ import { shallow } from 'enzyme';
import Breadcrumb from 'components/common/Breadcrumb'; import Breadcrumb from 'components/common/Breadcrumb';
import Flag from 'components/common/Flag'; import Flag from 'components/common/Flag';
import Tabs from 'components/common/Tabs'; import Tabs from 'components/common/Tabs';
import { mapDispatchToProps, mapStateToProps, ProfilePage, ProfilePageProps } from '../'; import { mapDispatchToProps, mapStateToProps, ProfilePage, ProfilePageProps, RouteProps } from '../';
import globalState from 'fixtures/globalState'; import globalState from 'fixtures/globalState';
import { getMockRouterProps } from 'fixtures/mockRouter';
import { ResourceType } from 'interfaces/Resources'; import { ResourceType } from 'interfaces/Resources';
import { import {
...@@ -23,7 +24,8 @@ import { ...@@ -23,7 +24,8 @@ import {
describe('ProfilePage', () => { describe('ProfilePage', () => {
const setup = (propOverrides?: Partial<ProfilePageProps>) => { const setup = (propOverrides?: Partial<ProfilePageProps>) => {
const props: Partial<ProfilePageProps> = { const routerProps = getMockRouterProps<RouteProps>({userId: 'test0'}, null);
const props: ProfilePageProps = {
user: globalState.user.profile.user, user: globalState.user.profile.user,
bookmarks: [ bookmarks: [
{ type: ResourceType.table }, { type: ResourceType.table },
...@@ -37,10 +39,10 @@ describe('ProfilePage', () => { ...@@ -37,10 +39,10 @@ describe('ProfilePage', () => {
getUserOwn: jest.fn(), getUserOwn: jest.fn(),
getUserRead: jest.fn(), getUserRead: jest.fn(),
getBookmarksForUser: jest.fn(), getBookmarksForUser: jest.fn(),
...routerProps,
...propOverrides ...propOverrides
}; };
// @ts-ignore : complains about match const wrapper = shallow<ProfilePage>(<ProfilePage {...props} />);
const wrapper = shallow<ProfilePage>(<ProfilePage {...props} match={{params: {userId: 'test0'}}}/>);
return { props, wrapper }; return { props, wrapper };
}; };
......
...@@ -11,36 +11,18 @@ import { ...@@ -11,36 +11,18 @@ import {
SYNTAX_ERROR_SPACING_SUFFIX, SYNTAX_ERROR_SPACING_SUFFIX,
} from '../constants'; } from '../constants';
import globalState from 'fixtures/globalState'; import globalState from 'fixtures/globalState';
import { getMockRouterProps } from 'fixtures/mockRouter';
describe('SearchBar', () => { describe('SearchBar', () => {
const valueChangeMockEvent = { target: { value: 'Data Resources' } }; const valueChangeMockEvent = { target: { value: 'Data Resources' } };
const submitMockEvent = { preventDefault: jest.fn() }; const submitMockEvent = { preventDefault: jest.fn() };
const setStateSpy = jest.spyOn(SearchBar.prototype, 'setState'); const setStateSpy = jest.spyOn(SearchBar.prototype, 'setState');
const routerProps = getMockRouterProps<any>(null, null);
const historyPushSpy = jest.spyOn(routerProps.history, 'push');
const setup = (propOverrides?: Partial<SearchBarProps>) => { const setup = (propOverrides?: Partial<SearchBarProps>) => {
const props: SearchBarProps = { const props: SearchBarProps = {
searchTerm: '', searchTerm: '',
history: { ...routerProps,
length: 2,
action: "POP",
location: jest.fn() as any,
push: jest.fn(),
replace: jest.fn(),
go: jest.fn(),
goBack: jest.fn(),
goForward: jest.fn(),
block: jest.fn(),
createHref: jest.fn(),
listen: jest.fn(),
},
location: {
search: '/search?searchTerm=testName&selectedTab=table&pageIndex=1',
pathname: 'mockstr',
state: jest.fn(),
hash: 'mockstr',
},
match: jest.fn() as any,
staticContext: jest.fn() as any,
...propOverrides ...propOverrides
}; };
const wrapper = shallow<SearchBar>(<SearchBar {...props} />) const wrapper = shallow<SearchBar>(<SearchBar {...props} />)
...@@ -101,23 +83,26 @@ describe('SearchBar', () => { ...@@ -101,23 +83,26 @@ describe('SearchBar', () => {
}); });
it('redirects back to home if searchTerm is empty', () => { it('redirects back to home if searchTerm is empty', () => {
historyPushSpy.mockClear();
// @ts-ignore: mocked events throw type errors // @ts-ignore: mocked events throw type errors
wrapper.instance().handleValueSubmit(submitMockEvent); wrapper.instance().handleValueSubmit(submitMockEvent);
expect(props.history.push).toHaveBeenCalledWith('/'); expect(historyPushSpy).toHaveBeenCalledWith('/');
}); });
it('submits with correct props if isFormValid()', () => { it('submits with correct props if isFormValid()', () => {
historyPushSpy.mockClear();
const { props, wrapper } = setup({ searchTerm: 'testTerm' }); const { props, wrapper } = setup({ searchTerm: 'testTerm' });
// @ts-ignore: mocked events throw type errors // @ts-ignore: mocked events throw type errors
wrapper.instance().handleValueSubmit(submitMockEvent); wrapper.instance().handleValueSubmit(submitMockEvent);
expect(props.history.push).toHaveBeenCalledWith(`/search?searchTerm=${wrapper.state().searchTerm}`); expect(historyPushSpy).toHaveBeenCalledWith(`/search?searchTerm=${wrapper.state().searchTerm}`);
}); });
it('does not submit if !isFormValid()', () => { it('does not submit if !isFormValid()', () => {
historyPushSpy.mockClear();
const { props, wrapper } = setup({ searchTerm: 'tag:tag1 tag:tag2' }); const { props, wrapper } = setup({ searchTerm: 'tag:tag1 tag:tag2' });
// @ts-ignore: mocked events throw type errors // @ts-ignore: mocked events throw type errors
wrapper.instance().handleValueSubmit(submitMockEvent); wrapper.instance().handleValueSubmit(submitMockEvent);
expect(props.history.push).not.toHaveBeenCalled(); expect(historyPushSpy).not.toHaveBeenCalled();
}); });
}); });
......
import * as React from 'react'; import * as React from 'react';
import * as DocumentTitle from 'react-document-title'; import * as DocumentTitle from 'react-document-title';
import * as History from 'history';
import { shallow } from 'enzyme'; import { shallow } from 'enzyme';
...@@ -28,10 +29,12 @@ import LoadingSpinner from 'components/common/LoadingSpinner'; ...@@ -28,10 +29,12 @@ import LoadingSpinner from 'components/common/LoadingSpinner';
import ResourceList from 'components/common/ResourceList'; import ResourceList from 'components/common/ResourceList';
import globalState from 'fixtures/globalState'; import globalState from 'fixtures/globalState';
import { getMockRouterProps } from 'fixtures/mockRouter';
describe('SearchPage', () => { describe('SearchPage', () => {
const setStateSpy = jest.spyOn(SearchPage.prototype, 'setState'); const setStateSpy = jest.spyOn(SearchPage.prototype, 'setState');
const setup = (propOverrides?: Partial<SearchPageProps>) => { const setup = (propOverrides?: Partial<SearchPageProps>, location?: Partial<History.Location>) => {
const routerProps = getMockRouterProps<any>(null, location);
const props: SearchPageProps = { const props: SearchPageProps = {
searchTerm: globalState.search.search_term, searchTerm: globalState.search.search_term,
isLoading: false, isLoading: false,
...@@ -40,27 +43,7 @@ describe('SearchPage', () => { ...@@ -40,27 +43,7 @@ describe('SearchPage', () => {
users: globalState.search.users, users: globalState.search.users,
searchAll: jest.fn(), searchAll: jest.fn(),
searchResource: jest.fn(), searchResource: jest.fn(),
history: { ...routerProps,
length: 2,
action: "POP",
location: jest.fn() as any,
push: jest.fn(),
replace: jest.fn(),
go: jest.fn(),
goBack: jest.fn(),
goForward: jest.fn(),
block: jest.fn(),
createHref: jest.fn(),
listen: jest.fn(),
},
location: {
search: '/search?searchTerm=testName&selectedTab=table&pageIndex=1',
pathname: 'mockstr',
state: jest.fn(),
hash: 'mockstr',
},
match: jest.fn() as any,
staticContext: jest.fn() as any,
...propOverrides, ...propOverrides,
}; };
const wrapper = shallow<SearchPage>(<SearchPage {...props} />) const wrapper = shallow<SearchPage>(<SearchPage {...props} />)
...@@ -86,13 +69,8 @@ describe('SearchPage', () => { ...@@ -86,13 +69,8 @@ describe('SearchPage', () => {
let updatePageUrlSpy; let updatePageUrlSpy;
beforeAll(() => { beforeAll(() => {
const setupResult = setup({ const setupResult = setup(null, {
location: {
search: '/search?searchTerm=testName&selectedTab=table&pageIndex=1', search: '/search?searchTerm=testName&selectedTab=table&pageIndex=1',
pathname: 'mockstr',
state: jest.fn(),
hash: 'mockstr',
}
}); });
props = setupResult.props; props = setupResult.props;
wrapper = setupResult.wrapper; wrapper = setupResult.wrapper;
...@@ -119,13 +97,8 @@ describe('SearchPage', () => { ...@@ -119,13 +97,8 @@ describe('SearchPage', () => {
describe('when searchTerm in params is valid', () => { describe('when searchTerm in params is valid', () => {
beforeAll(() => { beforeAll(() => {
updatePageUrlSpy.mockClear(); updatePageUrlSpy.mockClear();
const {props, wrapper} = setup({ const {props, wrapper} = setup(null, {
location: {
search: '/search?searchTerm=testName&selectedTab=table&pageIndex=1', search: '/search?searchTerm=testName&selectedTab=table&pageIndex=1',
pathname: 'mockstr',
state: jest.fn(),
hash: 'mockstr',
}
}); });
updatePageUrlSpy = jest.spyOn(wrapper.instance(), 'updatePageUrl'); updatePageUrlSpy = jest.spyOn(wrapper.instance(), 'updatePageUrl');
wrapper.instance().componentDidMount(); wrapper.instance().componentDidMount();
...@@ -146,13 +119,8 @@ describe('SearchPage', () => { ...@@ -146,13 +119,8 @@ describe('SearchPage', () => {
let updatePageUrlSpy; let updatePageUrlSpy;
beforeAll(() => { beforeAll(() => {
const {props, wrapper} = setup({ const {props, wrapper} = setup(null, {
location: {
search: '/search?searchTerm=testName', search: '/search?searchTerm=testName',
pathname: 'mockstr',
state: jest.fn(),
hash: 'mockstr',
}
}); });
mockSanitizedUrlParams = { 'term': 'testName', ' index': 0, 'currentTab': 'table' }; mockSanitizedUrlParams = { 'term': 'testName', ' index': 0, 'currentTab': 'table' };
getSanitizedUrlParamsSpy = jest.spyOn(wrapper.instance(), 'getSanitizedUrlParams').mockImplementation(() => { getSanitizedUrlParamsSpy = jest.spyOn(wrapper.instance(), 'getSanitizedUrlParams').mockImplementation(() => {
...@@ -170,13 +138,8 @@ describe('SearchPage', () => { ...@@ -170,13 +138,8 @@ describe('SearchPage', () => {
beforeAll(() => { beforeAll(() => {
searchAllSpy.mockClear(); searchAllSpy.mockClear();
updatePageUrlSpy.mockClear(); updatePageUrlSpy.mockClear();
const {props, wrapper} = setup({ const {props, wrapper} = setup(null, {
location: {
search: '/search?selectedTab=table&pageIndex=1', search: '/search?selectedTab=table&pageIndex=1',
pathname: 'mockstr',
state: jest.fn(),
hash: 'mockstr',
}
}); });
updatePageUrlSpy = jest.spyOn(wrapper.instance(), 'updatePageUrl'); updatePageUrlSpy = jest.spyOn(wrapper.instance(), 'updatePageUrl');
wrapper.instance().componentDidMount(); wrapper.instance().componentDidMount();
...@@ -194,13 +157,8 @@ describe('SearchPage', () => { ...@@ -194,13 +157,8 @@ describe('SearchPage', () => {
beforeAll(() => { beforeAll(() => {
searchAllSpy.mockClear(); searchAllSpy.mockClear();
updatePageUrlSpy.mockClear(); updatePageUrlSpy.mockClear();
const {props, wrapper} = setup({ const {props, wrapper} = setup(null, {
location: {
search: '/search?searchTerm=&selectedTab=table&pageIndex=1', search: '/search?searchTerm=&selectedTab=table&pageIndex=1',
pathname: 'mockstr',
state: jest.fn(),
hash: 'mockstr',
}
}); });
updatePageUrlSpy = jest.spyOn(wrapper.instance(), 'updatePageUrl'); updatePageUrlSpy = jest.spyOn(wrapper.instance(), 'updatePageUrl');
wrapper.instance().componentDidMount(); wrapper.instance().componentDidMount();
...@@ -231,13 +189,8 @@ describe('SearchPage', () => { ...@@ -231,13 +189,8 @@ describe('SearchPage', () => {
let props; let props;
let wrapper; let wrapper;
beforeAll(() => { beforeAll(() => {
const setupResult = setup({ const setupResult = setup(null, {
location: {
search: '/search?searchTerm=current&selectedTab=table&pageIndex=0', search: '/search?searchTerm=current&selectedTab=table&pageIndex=0',
pathname: 'mockstr',
state: jest.fn(),
hash: 'mockstr',
}
}); });
props = setupResult.props; props = setupResult.props;
wrapper = setupResult.wrapper; wrapper = setupResult.wrapper;
...@@ -300,13 +253,8 @@ describe('SearchPage', () => { ...@@ -300,13 +253,8 @@ describe('SearchPage', () => {
let mockSelectedTab; let mockSelectedTab;
beforeAll(() => { beforeAll(() => {
const setupResult = setup({ const setupResult = setup(null, {
location: {
search: '/search?searchTerm=current&selectedTab=table&pageIndex=0', search: '/search?searchTerm=current&selectedTab=table&pageIndex=0',
pathname: 'mockstr',
state: jest.fn(),
hash: 'mockstr',
}
}); });
props = setupResult.props; props = setupResult.props;
wrapper = setupResult.wrapper; wrapper = setupResult.wrapper;
......
...@@ -57,10 +57,9 @@ describe('TableListItem', () => { ...@@ -57,10 +57,9 @@ describe('TableListItem', () => {
expect(wrapper.find('.content').children().at(1).children().at(0).text()).toEqual('Last Updated'); expect(wrapper.find('.content').children().at(1).children().at(0).text()).toEqual('Last Updated');
}); });
/*it('renders getDateLabel value', () => { it('renders getDateLabel value', () => {
wrapper.update(); expect(wrapper.find('.content').children().at(1).children().at(1).text()).toEqual(wrapper.instance().getDateLabel());
expect(wrapper.find('.content').children().at(1).children().at(1).text()).toEqual('Mar 29, 2019'); });
});*/
}); });
describe('if props.table does not have last_updated_epoch', () => { describe('if props.table does not have last_updated_epoch', () => {
...@@ -80,13 +79,13 @@ describe('TableListItem', () => { ...@@ -80,13 +79,13 @@ describe('TableListItem', () => {
}); });
}); });
/* Note: Jest will convert date to UTC, expect to see different strings for an epoch value in the tests vs UI*/ /* Note: Jest is configured to use UTC */
/*describe('getDateLabel', () => { describe('getDateLabel', () => {
it('getDateLabel returns correct string', () => { it('getDateLabel returns correct string', () => {
const { props, wrapper } = setup(); const { props, wrapper } = setup();
expect(wrapper.instance().getDateLabel()).toEqual('Mar 29, 2019'); expect(wrapper.instance().getDateLabel()).toEqual('Mar 29, 2019');
}); });
});*/ });
describe('getLink', () => { describe('getLink', () => {
it('getLink returns correct string', () => { it('getLink returns correct string', () => {
......
import { RouteComponentProps } from 'react-router';
import * as History from 'history';
// Mock React-Router
export function getMockRouterProps<P>(data: P, location: Partial<History.Location>): RouteComponentProps<P> {
const mockLocation: History.Location = {
hash: '',
key: '',
pathname: '',
search: '',
state: {},
...location,
};
const props: RouteComponentProps<P> = {
match: {
isExact: true,
params: data,
path: '',
url: '',
},
location: mockLocation,
history: {
length: 2,
action: 'POP',
location: mockLocation,
push: () => {},
replace: null,
go: null,
goBack: null,
goForward: null,
block: null,
createHref: null,
listen: null,
},
staticContext: {
}
};
return props;
};
...@@ -10,14 +10,14 @@ ...@@ -10,14 +10,14 @@
"scripts": { "scripts": {
"build": "TS_NODE_PROJECT='tsconfig-for-webpack.json' webpack -p --progress --config webpack.prod.ts", "build": "TS_NODE_PROJECT='tsconfig-for-webpack.json' webpack -p --progress --config webpack.prod.ts",
"dev-build": "TS_NODE_PROJECT='tsconfig-for-webpack.json' webpack -d --progress --config webpack.dev.ts", "dev-build": "TS_NODE_PROJECT='tsconfig-for-webpack.json' webpack -d --progress --config webpack.dev.ts",
"test": "jest --coverage --collectCoverageFrom=js/**/*.{js,jsx,ts,tsx}", "test": "TZ=UTC jest --coverage --collectCoverageFrom=js/**/*.{js,jsx,ts,tsx}",
"test-nocov": "jest", "test-nocov": "TZ=UTC jest",
"watch": "TS_NODE_PROJECT='tsconfig-for-webpack.json' webpack -d --progress --config webpack.dev.ts --watch", "watch": "TS_NODE_PROJECT='tsconfig-for-webpack.json' webpack -d --progress --config webpack.dev.ts --watch",
"lint": "npm run eslint && npm run tslint", "lint": "npm run eslint && npm run tslint",
"lint-fix": "npm run eslint-fix && npm run tslint-fix", "lint-fix": "npm run eslint-fix && npm run tslint-fix",
"eslint": "eslint --ignore-path=.eslintignore --ext .js,.jsx .", "eslint": "eslint --ignore-path=.eslintignore --ext .js,.jsx .",
"eslint-fix": "eslint --fix --ignore-path=.eslintignore --ext .js,.jsx .", "eslint-fix": "eslint --fix --ignore-path=.eslintignore --ext .js,.jsx .",
"test:watch": "jest --watch", "test:watch": "TZ=UTC jest --watch",
"tsc": "tsc", "tsc": "tsc",
"tslint": "tslint --project .", "tslint": "tslint --project .",
"tslint-fix": "tslint --fix --project ." "tslint-fix": "tslint --fix --project ."
......
# Recommended Practices # Recommended Practices
This document serves as reference for current practices and patterns that we want to standardize across Amundsen's frontend application code. Below, we provide high-level guidelines targeted towards new contributors or any contributor who does not yet have domain knowledge in a particular framework or core library. This document is **not** intended to provide an exhaustive checklist for completing certain tasks. This document serves as reference for current practices and patterns that we want to standardize across Amundsen's frontend application code. Below, we provide some high-level guidelines targeted towards new contributors or any contributor who does not yet have domain knowledge in a particular framework or core library. This document is **not** intended to provide an exhaustive checklist for completing certain tasks.
We aim to maintain a reasonably consistent code base through these practices and welcome PRs to update and improve these recommendations. We aim to maintain a reasonably consistent code base through these practices and welcome PRs to update and improve these recommendations.
## React Application ## Application
### Unit Testing ### Unit Testing
We use [Jest](https://jestjs.io/) as our test framework and leverage utility methods from [Enzyme](https://airbnb.io/enzyme/) to test React components. We use [Jest](https://jestjs.io/) as our test framework. We leverage utility methods from [Enzyme](https://airbnb.io/enzyme/) to test React components, and use [redux-saga-test-plan](https://github.com/jfairbank/redux-saga-test-plan#documentation) to test our `redux-saga` middleware logic.
#### Recommendations #### General
1. Leverage TypeScript to prevent bugs in unit tests and ensure that components are tested with data that matches their defined interfaces. Adding and updating test [fixtures](https://github.com/lyft/amundsenfrontendlibrary/tree/master/amundsen_application/static/js/fixtures) helps to provide re-useable pieces of typed test data for our code. 1. Leverage TypeScript to prevent bugs in unit tests and ensure that code is tested with inputs that match the defined interfaces and types. Adding and updating test [fixtures](https://github.com/lyft/amundsenfrontendlibrary/tree/master/amundsen_application/static/js/fixtures) helps to provide re-useable pieces of typed test data or mock implementations for this purpose.
2. Enzyme provides 3 different utilities for rendering React components for testing. We recommend using `shallow` rendering to start off. If a component has a use case that requires full DOM rendering, those cases will become apparent. See Enzyme's [api documentation](https://airbnb.io/enzyme/docs/api/) to read more about the recommendations for each option. 2. Leverage `beforeAll()`/`beforeEach()` for test setup when applicable. Leverage `afterAll()`/`afterEach` for test teardown when applicable to remove any side effects of the test block. For example if a mock implementation of a method was created in `beforeAll()`, the original implementation should be restored in `afterAll()`. See Jest's [setup-teardown documentation](https://jestjs.io/docs/en/setup-teardown) for further understanding.
3. Create a re-useable `setup()` function that will take any arguments needed to test conditional logic. 3. Use descriptive title strings. To assist with debugging we should be able to understand what a test is checking for and under what conditions.
4. Look for opportunities to organize tests a way such that one `setup()` can be used to test assertions that occur under the same conditions. For example, a test block for a method that has no conditional logic should only have one `setup()`. However, it is **not** recommended to share a `setup()` result across tests for different methods because we risk propagating side effects from one test block to another. 4. Become familiar with the variety of Jest [matchers](https://jestjs.io/docs/en/expect) that are available. Understanding the nuances of different matchers and the cases they are each ideal for assists with writing more robust tests. For example, there are many different ways to verify objects and the best matcher to use will depend on what exactly we are testing for. Examples:
5. Leverage `beforeAll()`/`beforeEach()` for test setup when applicable. Leverage `afterAll()`/`afterEach` for test teardown to remove any side effects of the test block. For example if a mock implementation of a method was created in `beforeAll()`, the original implementation should be restored in `afterAll()`. See Jest's [setup-teardown documentation](https://jestjs.io/docs/en/setup-teardown) for further understanding. * If asserting that `inputObject` is assigned to variable `x`, asserting the equivalence of `x` using `.toBe()` creates a more robust test for this case because `.toBe()` will verify that the variable is actually referencing the given object. Contrast this to a matcher like `.toEqual()` which will verify whether or not the object happens to have a particular set of properties and values. In this case using `.toEqual()` would risk hiding bugs where `x` is not actually referencing `inputObject` as expected, yet happens to have the same key value pairs perhaps due to side effects in the code.
6. Use descriptive title strings. To assist with debugging we should be able to understand what a test is checking for, and under what conditions. * If asserting that `outputObject` matches `expectedObject`, asserting the equivalence of each property on `outputObject` using `.toBe()` or asserting the equality of the two objects using `.toMatchObject()` is useful when we only care that certain values exist on `outputObject`. However if it matters that certain values **do not** exist on `outputObject` -- as is the case with reducer outputs -- `.toEqual()` is a more robust alternative as it compares all properties on both objects for equivalence.
7. Consider refactoring components or other files if they become burdensome to test. Potential options include (but are not limited to): 5. When testing logic that makes use of JavaScript's *Date* object, note that our Jest scripts are configured to run in the UTC timezone. Developers should either:
* Creating subcomponents for large components, or breaking down large functions. * Mock the *Date* object and its methods' return values, and run assertions based on the mock values.
* Create assertions knowing that the unit test suite will run as if we are in the UTC timezone.
6. Code coverage is important to track but it only informs us of what code was actually run and executed during the test. The onus is on the developer to focus on use case coverage and make sure that right assertions are run so that all logic is adequately tested.
#### React
1. Enzyme provides 3 different utilities for rendering React components for testing. We recommend using `shallow` rendering to start off. If a component has a use case that requires full DOM rendering, those cases will become apparent. See Enzyme's [api documentation](https://airbnb.io/enzyme/docs/api/) to read more about the recommendations for each option.
2. Create a re-useable `setup()` function that will take any arguments needed to test conditional logic.
3. Look for opportunities to organize tests a way such that one `setup()` can be used to test assertions that occur under the same conditions. For example, a test block for a method that has no conditional logic should only have one `setup()`. However, it is **not** recommended to share a `setup()` result across tests for different methods, or across tests for a method that has a dependency on a mutable piece of state. The reason is that we risk propagating side effects from one test block to another.
4. Consider refactoring components or other files if they become burdensome to test. Potential options include (but are not limited to):
* Create subcomponents for large components. This is also especially useful for reducing the burden of updating tests when component layouts are changed.
* Break down large functions into smaller functions. Unit test the logic of the smaller functions individually, and mock their results when testing the larger function.
* Export constants from a separate file for hardcoded values and import them into the relevant source files and test files. This is especially helpful for strings. * Export constants from a separate file for hardcoded values and import them into the relevant source files and test files. This is especially helpful for strings.
8. Code coverage is important to track but it only informs us of what code was actually run and executed during the test. The onus is on the developer to make sure that right assertions are run and that logic is adequately tested.
#### Redux
1. Because the majority of Redux code consists of functions, we unit test those methods as usual and ensure the functions produce the expected output for any given input. See Redux's documentation on testing [action creators](https://redux.js.org/recipes/writing-tests#action-creators), [async action creators](https://redux.js.org/recipes/writing-tests#async-action-creators), and [reducers](https://redux.js.org/recipes/writing-tests#reducers), or check out examples in our code.
2. `redux-saga` generator functions can be tested by iterating through it step-by-step and running assertions at each step, or by executing the entire saga and running assertions on the side effects. See redux-saga's documentation on [testing sagas](https://redux-saga.js.org/docs/advanced/Testing.html) for a wider breadth of examples.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment