1
0
mirror of https://github.com/kremalicious/metamask-extension.git synced 2024-11-21 17:37:01 +01:00

Use jest to run ui/**/*.test.js (#10885)

This commit is contained in:
Thomas Huang 2021-04-15 11:01:46 -07:00 committed by GitHub
parent 2f8908804a
commit b99c4fb5cf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
137 changed files with 4463 additions and 4943 deletions

View File

@ -108,14 +108,14 @@ module.exports = {
},
{
files: ['**/*.test.js'],
excludedFiles: ['ui/app/**/swaps/**/*.test.js'],
excludedFiles: ['ui/**/*.test.js'],
extends: ['@metamask/eslint-config-mocha'],
rules: {
'mocha/no-setup-in-describe': 'off',
},
},
{
files: ['ui/app/**/swaps/**/*.test.js'],
files: ['ui/**/*.test.js'],
extends: ['@metamask/eslint-config-jest'],
},
{

View File

@ -10,5 +10,5 @@ module.exports = {
},
},
setupFiles: ['./test/setup.js', './test/env.js'],
testMatch: ['<rootDir>/ui/app/**/swaps/**/*.test.js'],
testMatch: ['**/ui/**/?(*.)+(test).js'],
};

View File

@ -20,12 +20,12 @@
"forwarder": "node ./development/static-server.js ./node_modules/@metamask/forwarder/dist/ --port 9010",
"dapp-forwarder": "concurrently -k -n forwarder,dapp -p '[{time}][{name}]' 'yarn forwarder' 'yarn dapp'",
"sendwithprivatedapp": "node development/static-server.js test/e2e/send-eth-with-private-key-test --port 8080",
"test:unit": "mocha --exit --require test/env.js --require test/setup.js --ignore './ui/app/**/swaps/**/*.test.js' --recursive './{ui,app,shared}/**/*.test.js'",
"test:unit": "mocha --exit --require test/env.js --require test/setup.js --recursive './{app,shared}/**/*.test.js'",
"test:unit:global": "mocha --exit --require test/env.js --require test/setup.js --recursive test/unit-global/*.test.js",
"test:unit:jest": "jest",
"test:unit:jest:watch": "jest --watch",
"test:unit:jest:ci": "jest --maxWorkers=2",
"test:unit:lax": "mocha --exit --require test/env.js --require test/setup.js --ignore './app/scripts/controllers/permissions/*.test.js' --ignore './ui/app/**/swaps/**/*.test.js' --recursive './{ui,app,shared}/**/*.test.js'",
"test:unit:lax": "mocha --exit --require test/env.js --require test/setup.js --ignore './app/scripts/controllers/permissions/*.test.js' --recursive './{app,shared}/**/*.test.js'",
"test:unit:strict": "mocha --exit --require test/env.js --require test/setup.js --recursive './app/scripts/controllers/permissions/*.test.js'",
"test:unit:path": "mocha --exit --require test/env.js --require test/setup.js --recursive",
"test:e2e:chrome": "SELENIUM_BROWSER=chrome test/e2e/run-all.sh",

5
test/lib/tick.js Normal file
View File

@ -0,0 +1,5 @@
export function tick() {
return new Promise((resolve) => {
setTimeout(resolve, 0);
});
}

View File

@ -1,4 +1,3 @@
import assert from 'assert';
import React from 'react';
import { shallow } from 'enzyme';
import sinon from 'sinon';
@ -6,11 +5,11 @@ import * as utils from '../../../helpers/utils/util';
import Identicon from '../../ui/identicon';
import AccountListItem from './account-list-item';
describe('AccountListItem Component', function () {
describe('AccountListItem Component', () => {
let wrapper, propsMethodSpies, checksumAddressStub;
describe('render', function () {
before(function () {
describe('render', () => {
beforeAll(() => {
checksumAddressStub = sinon
.stub(utils, 'checksumAddress')
.returns('mockCheckSumAddress');
@ -18,7 +17,7 @@ describe('AccountListItem Component', function () {
handleClick: sinon.spy(),
};
});
beforeEach(function () {
beforeEach(() => {
wrapper = shallow(
<AccountListItem
account={{
@ -35,119 +34,113 @@ describe('AccountListItem Component', function () {
);
});
afterEach(function () {
afterEach(() => {
propsMethodSpies.handleClick.resetHistory();
checksumAddressStub.resetHistory();
});
after(function () {
afterAll(() => {
sinon.restore();
});
it('should render a div with the passed className', function () {
assert.strictEqual(wrapper.find('.mockClassName').length, 1);
assert(wrapper.find('.mockClassName').is('div'));
assert(wrapper.find('.mockClassName').hasClass('account-list-item'));
it('should render a div with the passed className', () => {
expect(wrapper.find('.mockClassName')).toHaveLength(1);
expect(wrapper.find('.mockClassName').is('div')).toStrictEqual(true);
expect(
wrapper.find('.mockClassName').hasClass('account-list-item'),
).toStrictEqual(true);
});
it('should call handleClick with the expected props when the root div is clicked', function () {
it('should call handleClick with the expected props when the root div is clicked', () => {
const { onClick } = wrapper.find('.mockClassName').props();
assert.strictEqual(propsMethodSpies.handleClick.callCount, 0);
expect(propsMethodSpies.handleClick.callCount).toStrictEqual(0);
onClick();
assert.strictEqual(propsMethodSpies.handleClick.callCount, 1);
assert.deepStrictEqual(propsMethodSpies.handleClick.getCall(0).args, [
expect(propsMethodSpies.handleClick.callCount).toStrictEqual(1);
expect(propsMethodSpies.handleClick.getCall(0).args).toStrictEqual([
{ address: 'mockAddress', name: 'mockName', balance: 'mockBalance' },
]);
});
it('should have a top row div', function () {
assert.strictEqual(
wrapper.find('.mockClassName > .account-list-item__top-row').length,
1,
);
assert(
it('should have a top row div', () => {
expect(
wrapper.find('.mockClassName > .account-list-item__top-row'),
).toHaveLength(1);
expect(
wrapper.find('.mockClassName > .account-list-item__top-row').is('div'),
);
).toStrictEqual(true);
});
it('should have an identicon, name and icon in the top row', function () {
it('should have an identicon, name and icon in the top row', () => {
const topRow = wrapper.find(
'.mockClassName > .account-list-item__top-row',
);
assert.strictEqual(topRow.find(Identicon).length, 1);
assert.strictEqual(
topRow.find('.account-list-item__account-name').length,
1,
);
assert.strictEqual(topRow.find('.account-list-item__icon').length, 1);
expect(topRow.find(Identicon)).toHaveLength(1);
expect(topRow.find('.account-list-item__account-name')).toHaveLength(1);
expect(topRow.find('.account-list-item__icon')).toHaveLength(1);
});
it('should show the account name if it exists', function () {
it('should show the account name if it exists', () => {
const topRow = wrapper.find(
'.mockClassName > .account-list-item__top-row',
);
assert.strictEqual(
expect(
topRow.find('.account-list-item__account-name').text(),
'mockName',
);
).toStrictEqual('mockName');
});
it('should show the account address if there is no name', function () {
it('should show the account address if there is no name', () => {
wrapper.setProps({ account: { address: 'addressButNoName' } });
const topRow = wrapper.find(
'.mockClassName > .account-list-item__top-row',
);
assert.strictEqual(
expect(
topRow.find('.account-list-item__account-name').text(),
'addressButNoName',
);
).toStrictEqual('addressButNoName');
});
it('should render the passed icon', function () {
it('should render the passed icon', () => {
const topRow = wrapper.find(
'.mockClassName > .account-list-item__top-row',
);
assert(topRow.find('.account-list-item__icon').childAt(0).is('i'));
assert(
expect(
topRow.find('.account-list-item__icon').childAt(0).is('i'),
).toStrictEqual(true);
expect(
topRow.find('.account-list-item__icon').childAt(0).hasClass('mockIcon'),
);
).toStrictEqual(true);
});
it('should not render an icon if none is passed', function () {
it('should not render an icon if none is passed', () => {
wrapper.setProps({ icon: null });
const topRow = wrapper.find(
'.mockClassName > .account-list-item__top-row',
);
assert.strictEqual(topRow.find('.account-list-item__icon').length, 0);
expect(topRow.find('.account-list-item__icon')).toHaveLength(0);
});
it('should render the account address as a checksumAddress if displayAddress is true and name is provided', function () {
it('should render the account address as a checksumAddress if displayAddress is true and name is provided', () => {
wrapper.setProps({ displayAddress: true });
assert.strictEqual(
wrapper.find('.account-list-item__account-address').length,
expect(wrapper.find('.account-list-item__account-address')).toHaveLength(
1,
);
assert.strictEqual(
expect(
wrapper.find('.account-list-item__account-address').text(),
'mockCheckSumAddress',
);
assert.deepStrictEqual(checksumAddressStub.getCall(0).args, [
).toStrictEqual('mockCheckSumAddress');
expect(checksumAddressStub.getCall(0).args).toStrictEqual([
'mockAddress',
]);
});
it('should not render the account address as a checksumAddress if displayAddress is false', function () {
it('should not render the account address as a checksumAddress if displayAddress is false', () => {
wrapper.setProps({ displayAddress: false });
assert.strictEqual(
wrapper.find('.account-list-item__account-address').length,
expect(wrapper.find('.account-list-item__account-address')).toHaveLength(
0,
);
});
it('should not render the account address as a checksumAddress if name is not provided', function () {
it('should not render the account address as a checksumAddress if name is not provided', () => {
wrapper.setProps({ account: { address: 'someAddressButNoName' } });
assert.strictEqual(
wrapper.find('.account-list-item__account-address').length,
expect(wrapper.find('.account-list-item__account-address')).toHaveLength(
0,
);
});

View File

@ -1,4 +1,3 @@
import assert from 'assert';
import React from 'react';
import sinon from 'sinon';
import configureMockStore from 'redux-mock-store';
@ -6,7 +5,7 @@ import { Provider } from 'react-redux';
import { mountWithRouter } from '../../../../../test/lib/render-helpers';
import AccountMenu from '.';
describe('Account Menu', function () {
describe('Account Menu', () => {
let wrapper;
const mockStore = {
@ -57,7 +56,7 @@ describe('Account Menu', function () {
},
};
before(function () {
beforeAll(() => {
wrapper = mountWithRouter(
<Provider store={store}>
<AccountMenu.WrappedComponent {...props} />
@ -66,136 +65,137 @@ describe('Account Menu', function () {
);
});
afterEach(function () {
afterEach(() => {
props.toggleAccountMenu.resetHistory();
props.history.push.resetHistory();
});
describe('Render Content', function () {
it('returns account name from identities', function () {
describe('Render Content', () => {
it('returns account name from identities', () => {
const accountName = wrapper.find('.account-menu__name');
assert.strictEqual(accountName.length, 2);
expect(accountName).toHaveLength(2);
});
it('renders user preference currency display balance from account balance', function () {
it('renders user preference currency display balance from account balance', () => {
const accountBalance = wrapper.find(
'.currency-display-component.account-menu__balance',
);
assert.strictEqual(accountBalance.length, 2);
expect(accountBalance).toHaveLength(2);
});
it('simulate click', function () {
it('simulate click', () => {
const click = wrapper.find(
'.account-menu__account.account-menu__item--clickable',
);
click.first().simulate('click');
assert(props.showAccountDetail.calledOnce);
assert.strictEqual(
props.showAccountDetail.getCall(0).args[0],
expect(props.showAccountDetail.calledOnce).toStrictEqual(true);
expect(props.showAccountDetail.getCall(0).args[0]).toStrictEqual(
'0xAddress',
);
});
it('render imported account label', function () {
it('render imported account label', () => {
const importedAccount = wrapper.find('.keyring-label.allcaps');
assert.strictEqual(importedAccount.text(), 'imported');
expect(importedAccount.text()).toStrictEqual('imported');
});
});
describe('Log Out', function () {
describe('Log Out', () => {
let logout;
it('logout', function () {
it('logout', () => {
logout = wrapper.find('.account-menu__lock-button');
assert.strictEqual(logout.length, 1);
expect(logout).toHaveLength(1);
});
it('simulate click', function () {
it('simulate click', () => {
logout.simulate('click');
assert(props.lockMetamask.calledOnce);
assert.strictEqual(props.history.push.getCall(0).args[0], '/');
expect(props.lockMetamask.calledOnce).toStrictEqual(true);
expect(props.history.push.getCall(0).args[0]).toStrictEqual('/');
});
});
describe('Create Account', function () {
describe('Create Account', () => {
let createAccount;
it('renders create account item', function () {
it('renders create account item', () => {
createAccount = wrapper.find({ text: 'createAccount' });
assert.strictEqual(createAccount.length, 1);
expect(createAccount).toHaveLength(1);
});
it('calls toggle menu and push new-account route to history', function () {
it('calls toggle menu and push new-account route to history', () => {
createAccount.simulate('click');
assert(props.toggleAccountMenu.calledOnce);
assert.strictEqual(props.history.push.getCall(0).args[0], '/new-account');
expect(props.toggleAccountMenu.calledOnce).toStrictEqual(true);
expect(props.history.push.getCall(0).args[0]).toStrictEqual(
'/new-account',
);
});
});
describe('Import Account', function () {
describe('Import Account', () => {
let importAccount;
it('renders import account item', function () {
it('renders import account item', () => {
importAccount = wrapper.find({ text: 'importAccount' });
assert.strictEqual(importAccount.length, 1);
expect(importAccount).toHaveLength(1);
});
it('calls toggle menu and push /new-account/import route to history', function () {
it('calls toggle menu and push /new-account/import route to history', () => {
importAccount.simulate('click');
assert(props.toggleAccountMenu.calledOnce);
assert(props.history.push.getCall(0).args[0], '/new-account/import');
expect(props.toggleAccountMenu.calledOnce).toStrictEqual(true);
expect(props.history.push.getCall(0).args[0]).toStrictEqual(
'/new-account/import',
);
});
});
describe('Connect Hardware Wallet', function () {
describe('Connect Hardware Wallet', () => {
let connectHardwareWallet;
it('renders import account item', function () {
it('renders import account item', () => {
connectHardwareWallet = wrapper.find({ text: 'connectHardwareWallet' });
assert.strictEqual(connectHardwareWallet.length, 1);
expect(connectHardwareWallet).toHaveLength(1);
});
it('calls toggle menu and push /new-account/connect route to history', function () {
it('calls toggle menu and push /new-account/connect route to history', () => {
connectHardwareWallet.simulate('click');
assert(props.toggleAccountMenu.calledOnce);
assert.strictEqual(
props.history.push.getCall(0).args[0],
expect(props.toggleAccountMenu.calledOnce).toStrictEqual(true);
expect(props.history.push.getCall(0).args[0]).toStrictEqual(
'/new-account/connect',
);
});
});
describe('Info & Help', function () {
describe('Info & Help', () => {
let infoHelp;
it('renders import account item', function () {
it('renders import account item', () => {
infoHelp = wrapper.find({ text: 'infoHelp' });
assert.strictEqual(infoHelp.length, 1);
expect(infoHelp).toHaveLength(1);
});
it('calls toggle menu and push /new-account/connect route to history', function () {
it('calls toggle menu and push /new-account/connect route to history', () => {
infoHelp.simulate('click');
assert(props.toggleAccountMenu.calledOnce);
assert.strictEqual(
props.history.push.getCall(0).args[0],
expect(props.toggleAccountMenu.calledOnce).toStrictEqual(true);
expect(props.history.push.getCall(0).args[0]).toStrictEqual(
'/settings/about-us',
);
});
});
describe('Settings', function () {
describe('Settings', () => {
let settings;
it('renders import account item', function () {
it('renders import account item', () => {
settings = wrapper.find({ text: 'settings' });
assert.strictEqual(settings.length, 1);
expect(settings).toHaveLength(1);
});
it('calls toggle menu and push /new-account/connect route to history', function () {
it('calls toggle menu and push /new-account/connect route to history', () => {
settings.simulate('click');
assert(props.toggleAccountMenu.calledOnce);
assert.strictEqual(props.history.push.getCall(0).args[0], '/settings');
expect(props.toggleAccountMenu.calledOnce).toStrictEqual(true);
expect(props.history.push.getCall(0).args[0]).toStrictEqual('/settings');
});
});
});

View File

@ -1,4 +1,3 @@
import assert from 'assert';
import React from 'react';
import sinon from 'sinon';
@ -7,13 +6,14 @@ import thunk from 'redux-thunk';
import { fireEvent } from '@testing-library/react';
import configureMockStore from 'redux-mock-store';
import { tick } from '../../../../../../test/lib/tick';
import { renderWithProvider } from '../../../../../../test/lib/render-helpers';
import * as actions from '../../../../store/actions';
import { KOVAN_CHAIN_ID } from '../../../../../../shared/constants/network';
import UnconnectedAccountAlert from '.';
describe('Unconnected Account Alert', function () {
describe('Unconnected Account Alert', () => {
const selectedAddress = '0xec1adf982415d2ef5ec55899b9bfb8bc0f29251b';
const identities = {
@ -105,11 +105,11 @@ describe('Unconnected Account Alert', function () {
},
};
afterEach(function () {
afterEach(() => {
sinon.restore();
});
it('checks that checkbox is checked', function () {
it('checks that checkbox is checked', () => {
const store = configureMockStore()(mockState);
const { getByRole } = renderWithProvider(
@ -119,12 +119,12 @@ describe('Unconnected Account Alert', function () {
const dontShowCheckbox = getByRole('checkbox');
assert.strictEqual(dontShowCheckbox.checked, false);
expect(dontShowCheckbox.checked).toStrictEqual(false);
fireEvent.click(dontShowCheckbox);
assert.strictEqual(dontShowCheckbox.checked, true);
expect(dontShowCheckbox.checked).toStrictEqual(true);
});
it('clicks dismiss button and calls dismissAlert action', function () {
it('clicks dismiss button and calls dismissAlert action', () => {
const store = configureMockStore()(mockState);
const { getByText } = renderWithProvider(
@ -135,13 +135,12 @@ describe('Unconnected Account Alert', function () {
const dismissButton = getByText(/dismiss/u);
fireEvent.click(dismissButton);
assert.strictEqual(
store.getActions()[0].type,
expect(store.getActions()[0].type).toStrictEqual(
'unconnectedAccount/dismissAlert',
);
});
it('clicks Dont Show checkbox and dismiss to call disable alert request action', async function () {
it('clicks Dont Show checkbox and dismiss to call disable alert request action', async () => {
sinon.stub(actions, 'setAlertEnabledness').returns(() => Promise.resolve());
const store = configureMockStore([thunk])(mockState);
@ -157,15 +156,13 @@ describe('Unconnected Account Alert', function () {
fireEvent.click(dontShowCheckbox);
fireEvent.click(dismissButton);
setImmediate(() => {
assert.strictEqual(
store.getActions()[0].type,
'unconnectedAccount/disableAlertRequested',
);
assert.strictEqual(
store.getActions()[1].type,
'unconnectedAccount/disableAlertSucceeded',
);
});
await tick();
expect(store.getActions()[0].type).toStrictEqual(
'unconnectedAccount/disableAlertRequested',
);
expect(store.getActions()[1].type).toStrictEqual(
'unconnectedAccount/disableAlertSucceeded',
);
});
});

View File

@ -1,4 +1,3 @@
import assert from 'assert';
import React from 'react';
import sinon from 'sinon';
import { shallow } from 'enzyme';
@ -6,7 +5,7 @@ import MetaFoxLogo from '../../ui/metafox-logo';
import NetworkDisplay from '../network-display';
import AppHeader from './app-header.container';
describe('App Header', function () {
describe('App Header', () => {
let wrapper;
const props = {
@ -26,7 +25,7 @@ describe('App Header', function () {
isUnlocked: true,
};
beforeEach(function () {
beforeEach(() => {
wrapper = shallow(<AppHeader.WrappedComponent {...props} />, {
context: {
t: (str) => str,
@ -35,32 +34,31 @@ describe('App Header', function () {
});
});
afterEach(function () {
afterEach(() => {
props.toggleAccountMenu.resetHistory();
});
describe('App Header Logo', function () {
it('routes to default route when logo is clicked', function () {
describe('App Header Logo', () => {
it('routes to default route when logo is clicked', () => {
const appLogo = wrapper.find(MetaFoxLogo);
appLogo.simulate('click');
assert(props.history.push.calledOnce);
assert.strictEqual(props.history.push.getCall(0).args[0], '/');
expect(props.history.push.calledOnce).toStrictEqual(true);
expect(props.history.push.getCall(0).args[0]).toStrictEqual('/');
});
});
describe('Network', function () {
it('shows network dropdown when networkDropdownOpen is false', function () {
describe('Network', () => {
it('shows network dropdown when networkDropdownOpen is false', () => {
const network = wrapper.find(NetworkDisplay);
network.simulate('click', {
preventDefault: () => undefined,
stopPropagation: () => undefined,
});
assert(props.showNetworkDropdown.calledOnce);
expect(props.showNetworkDropdown.calledOnce).toStrictEqual(true);
});
it('hides network dropdown when networkDropdownOpen is true', function () {
it('hides network dropdown when networkDropdownOpen is true', () => {
wrapper.setProps({ networkDropdownOpen: true });
const network = wrapper.find(NetworkDisplay);
@ -69,28 +67,28 @@ describe('App Header', function () {
stopPropagation: () => undefined,
});
assert(props.hideNetworkDropdown.calledOnce);
expect(props.hideNetworkDropdown.calledOnce).toStrictEqual(true);
});
it('hides network indicator', function () {
it('hides network indicator', () => {
wrapper.setProps({ hideNetworkIndicator: true });
const network = wrapper.find({ network: 'test' });
assert.strictEqual(network.length, 0);
const network = wrapper.find(NetworkDisplay);
expect(network).toHaveLength(0);
});
});
describe('Account Menu', function () {
it('toggles account menu', function () {
describe('Account Menu', () => {
it('toggles account menu', () => {
const accountMenu = wrapper.find('.account-menu__icon');
accountMenu.simulate('click');
assert(props.toggleAccountMenu.calledOnce);
expect(props.toggleAccountMenu.calledOnce).toStrictEqual(true);
});
it('does not toggle account menu when disabled', function () {
it('does not toggle account menu when disabled', () => {
wrapper.setProps({ disabled: true });
const accountMenu = wrapper.find('.account-menu__icon');
accountMenu.simulate('click');
assert(props.toggleAccountMenu.notCalled);
expect(props.toggleAccountMenu.notCalled).toStrictEqual(true);
});
});
});

View File

@ -1,4 +1,3 @@
import assert from 'assert';
import React from 'react';
import { shallow } from 'enzyme';
import sinon from 'sinon';
@ -8,11 +7,11 @@ const propsMethodSpies = {
onHeaderClick: sinon.spy(),
};
describe('Confirm Detail Row Component', function () {
describe('render', function () {
describe('Confirm Detail Row Component', () => {
describe('render', () => {
let wrapper;
beforeEach(function () {
beforeEach(() => {
wrapper = shallow(
<ConfirmDetailRow
errorType="mockErrorType"
@ -28,69 +27,63 @@ describe('Confirm Detail Row Component', function () {
);
});
it('should render a div with a confirm-detail-row class', function () {
assert.strictEqual(wrapper.find('div.confirm-detail-row').length, 1);
it('should render a div with a confirm-detail-row class', () => {
expect(wrapper.find('div.confirm-detail-row')).toHaveLength(1);
});
it('should render the label as a child of the confirm-detail-row__label', function () {
assert.strictEqual(
it('should render the label as a child of the confirm-detail-row__label', () => {
expect(
wrapper
.find('.confirm-detail-row > .confirm-detail-row__label')
.childAt(0)
.text(),
'mockLabel',
);
).toStrictEqual('mockLabel');
});
it('should render the headerText as a child of the confirm-detail-row__header-text', function () {
assert.strictEqual(
it('should render the headerText as a child of the confirm-detail-row__header-text', () => {
expect(
wrapper
.find(
'.confirm-detail-row__details > .confirm-detail-row__header-text',
)
.childAt(0)
.text(),
'mockHeaderText',
);
).toStrictEqual('mockHeaderText');
});
it('should render the primaryText as a child of the confirm-detail-row__primary', function () {
assert.strictEqual(
it('should render the primaryText as a child of the confirm-detail-row__primary', () => {
expect(
wrapper
.find('.confirm-detail-row__details > .confirm-detail-row__primary')
.childAt(0)
.text(),
'mockFiatText',
);
).toStrictEqual('mockFiatText');
});
it('should render the ethText as a child of the confirm-detail-row__secondary', function () {
assert.strictEqual(
it('should render the ethText as a child of the confirm-detail-row__secondary', () => {
expect(
wrapper
.find('.confirm-detail-row__details > .confirm-detail-row__secondary')
.childAt(0)
.text(),
'mockEthText',
);
).toStrictEqual('mockEthText');
});
it('should set the fiatTextColor on confirm-detail-row__primary', function () {
assert.strictEqual(
it('should set the fiatTextColor on confirm-detail-row__primary', () => {
expect(
wrapper.find('.confirm-detail-row__primary').props().style.color,
'mockColor',
);
).toStrictEqual('mockColor');
});
it('should assure the confirm-detail-row__header-text classname is correct', function () {
assert.strictEqual(
it('should assure the confirm-detail-row__header-text classname is correct', () => {
expect(
wrapper.find('.confirm-detail-row__header-text').props().className,
'confirm-detail-row__header-text mockHeaderClass',
);
).toStrictEqual('confirm-detail-row__header-text mockHeaderClass');
});
it('should call onHeaderClick when headerText div gets clicked', function () {
it('should call onHeaderClick when headerText div gets clicked', () => {
wrapper.find('.confirm-detail-row__header-text').props().onClick();
assert.ok(propsMethodSpies.onHeaderClick.calledOnce);
expect(propsMethodSpies.onHeaderClick.calledOnce).toStrictEqual(true);
});
});
});

View File

@ -1,4 +1,3 @@
import assert from 'assert';
import React from 'react';
import { shallow } from 'enzyme';
import sinon from 'sinon';
@ -9,9 +8,9 @@ import ConfirmPageContainerHeader from './confirm-page-container-header.componen
const util = require('../../../../../../app/scripts/lib/util');
describe('Confirm Detail Row Component', function () {
describe('render', function () {
it('should render a div with a confirm-page-container-header class', function () {
describe('Confirm Detail Row Component', () => {
describe('render', () => {
it('should render a div with a confirm-page-container-header class', () => {
const stub = sinon
.stub(util, 'getEnvironmentType')
.callsFake(() => 'popup');
@ -27,14 +26,11 @@ describe('Confirm Detail Row Component', function () {
/>
</Provider>,
);
assert.strictEqual(
wrapper.html().includes('confirm-page-container-header'),
true,
);
expect(wrapper.html()).toContain('confirm-page-container-header');
stub.restore();
});
it('should only render children when fullscreen and showEdit is false', function () {
it('should only render children when fullscreen and showEdit is false', () => {
const stub = sinon
.stub(util, 'getEnvironmentType')
.callsFake(() => 'fullscreen');
@ -52,11 +48,8 @@ describe('Confirm Detail Row Component', function () {
</ConfirmPageContainerHeader>
</Provider>,
);
assert.strictEqual(wrapper.html().includes('nested-test-class'), true);
assert.strictEqual(
wrapper.html().includes('confirm-page-container-header'),
false,
);
expect(wrapper.html()).toContain('nested-test-class');
expect(wrapper.html()).not.toContain('confirm-page-container-header');
stub.restore();
});
});

View File

@ -1,15 +1,14 @@
import assert from 'assert';
import React from 'react';
import sinon from 'sinon';
import { shallow } from 'enzyme';
import { DropdownMenuItem } from './dropdown';
describe('Dropdown', function () {
describe('Dropdown', () => {
let wrapper;
const onClickSpy = sinon.spy();
const closeMenuSpy = sinon.spy();
beforeEach(function () {
beforeEach(() => {
wrapper = shallow(
<DropdownMenuItem
onClick={onClickSpy}
@ -19,17 +18,17 @@ describe('Dropdown', function () {
);
});
it('renders li with dropdown-menu-item class', function () {
assert.strictEqual(wrapper.find('li.dropdown-menu-item').length, 1);
it('renders li with dropdown-menu-item class', () => {
expect(wrapper.find('li.dropdown-menu-item')).toHaveLength(1);
});
it('adds style based on props passed', function () {
assert.strictEqual(wrapper.prop('style').test, 'style');
it('adds style based on props passed', () => {
expect(wrapper.prop('style').test).toStrictEqual('style');
});
it('simulates click event and calls onClick and closeMenu', function () {
it('simulates click event and calls onClick and closeMenu', () => {
wrapper.prop('onClick')();
assert.strictEqual(onClickSpy.callCount, 1);
assert.strictEqual(closeMenuSpy.callCount, 1);
expect(onClickSpy.callCount).toStrictEqual(1);
expect(closeMenuSpy.callCount).toStrictEqual(1);
});
});

View File

@ -1,4 +1,3 @@
import assert from 'assert';
import React from 'react';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
@ -7,11 +6,11 @@ import ColorIndicator from '../../ui/color-indicator';
import NetworkDropdown from './network-dropdown';
import { DropdownMenuItem } from './dropdown';
describe('Network Dropdown', function () {
describe('Network Dropdown', () => {
let wrapper;
const createMockStore = configureMockStore([thunk]);
describe('NetworkDropdown in appState in false', function () {
describe('NetworkDropdown in appState in false', () => {
const mockState = {
metamask: {
network: '1',
@ -26,20 +25,20 @@ describe('Network Dropdown', function () {
const store = createMockStore(mockState);
beforeEach(function () {
beforeEach(() => {
wrapper = mountWithRouter(<NetworkDropdown store={store} />);
});
it('checks for network droppo class', function () {
assert.strictEqual(wrapper.find('.network-droppo').length, 1);
it('checks for network droppo class', () => {
expect(wrapper.find('.network-droppo')).toHaveLength(1);
});
it('renders only one child when networkDropdown is false in state', function () {
assert.strictEqual(wrapper.children().length, 1);
it('renders only one child when networkDropdown is false in state', () => {
expect(wrapper.children()).toHaveLength(1);
});
});
describe('NetworkDropdown in appState is true', function () {
describe('NetworkDropdown in appState is true', () => {
const mockState = {
metamask: {
network: '1',
@ -57,54 +56,55 @@ describe('Network Dropdown', function () {
};
const store = createMockStore(mockState);
beforeEach(function () {
beforeEach(() => {
wrapper = mountWithRouter(<NetworkDropdown store={store} />);
});
it('renders 8 DropDownMenuItems ', function () {
assert.strictEqual(wrapper.find(DropdownMenuItem).length, 8);
it('renders 8 DropDownMenuItems', () => {
expect(wrapper.find(DropdownMenuItem)).toHaveLength(8);
});
it('checks background color for first ColorIndicator', function () {
it('checks background color for first ColorIndicator', () => {
const colorIndicator = wrapper.find(ColorIndicator).at(0);
assert.strictEqual(colorIndicator.prop('color'), 'mainnet');
assert.strictEqual(colorIndicator.prop('borderColor'), 'mainnet');
expect(colorIndicator.prop('color')).toStrictEqual('mainnet');
expect(colorIndicator.prop('borderColor')).toStrictEqual('mainnet');
});
it('checks background color for second ColorIndicator', function () {
it('checks background color for second ColorIndicator', () => {
const colorIndicator = wrapper.find(ColorIndicator).at(1);
assert.strictEqual(colorIndicator.prop('color'), 'ropsten');
assert.strictEqual(colorIndicator.prop('borderColor'), 'ropsten');
expect(colorIndicator.prop('color')).toStrictEqual('ropsten');
expect(colorIndicator.prop('borderColor')).toStrictEqual('ropsten');
});
it('checks background color for third ColorIndicator', function () {
it('checks background color for third ColorIndicator', () => {
const colorIndicator = wrapper.find(ColorIndicator).at(2);
assert.strictEqual(colorIndicator.prop('color'), 'kovan');
assert.strictEqual(colorIndicator.prop('borderColor'), 'kovan');
expect(colorIndicator.prop('color')).toStrictEqual('kovan');
expect(colorIndicator.prop('borderColor')).toStrictEqual('kovan');
});
it('checks background color for fourth ColorIndicator', function () {
it('checks background color for fourth ColorIndicator', () => {
const colorIndicator = wrapper.find(ColorIndicator).at(3);
assert.strictEqual(colorIndicator.prop('color'), 'rinkeby');
assert.strictEqual(colorIndicator.prop('borderColor'), 'rinkeby');
expect(colorIndicator.prop('color')).toStrictEqual('rinkeby');
expect(colorIndicator.prop('borderColor')).toStrictEqual('rinkeby');
});
it('checks background color for fifth ColorIndicator', function () {
it('checks background color for fifth ColorIndicator', () => {
const colorIndicator = wrapper.find(ColorIndicator).at(4);
assert.strictEqual(colorIndicator.prop('color'), 'goerli');
assert.strictEqual(colorIndicator.prop('borderColor'), 'goerli');
expect(colorIndicator.prop('color')).toStrictEqual('goerli');
expect(colorIndicator.prop('borderColor')).toStrictEqual('goerli');
});
it('checks background color for sixth ColorIndicator', function () {
it('checks background color for sixth ColorIndicator', () => {
const colorIndicator = wrapper.find(ColorIndicator).at(5);
const customNetworkGray = 'ui-2';
assert.strictEqual(colorIndicator.prop('color'), customNetworkGray);
assert.strictEqual(colorIndicator.prop('borderColor'), customNetworkGray);
expect(colorIndicator.prop('color')).toStrictEqual(customNetworkGray);
expect(colorIndicator.prop('borderColor')).toStrictEqual(
customNetworkGray,
);
});
it('checks dropdown for frequestRPCList from state', function () {
assert.strictEqual(
wrapper.find(DropdownMenuItem).at(6).text(),
it('checks dropdown for frequestRPCList from state', () => {
expect(wrapper.find(DropdownMenuItem).at(6).text()).toStrictEqual(
'✓http://localhost:7545',
);
});

View File

@ -1,10 +1,9 @@
import assert from 'assert';
import React from 'react';
import sinon from 'sinon';
import { mount } from 'enzyme';
import AdvancedTabContent from './advanced-gas-inputs.container';
describe('Advanced Gas Inputs', function () {
describe('Advanced Gas Inputs', () => {
let wrapper, clock;
const props = {
@ -20,7 +19,7 @@ describe('Advanced Gas Inputs', function () {
minimumGasLimit: 21000,
};
beforeEach(function () {
beforeEach(() => {
clock = sinon.useFakeTimers();
wrapper = mount(<AdvancedTabContent.WrappedComponent {...props} />, {
@ -30,93 +29,94 @@ describe('Advanced Gas Inputs', function () {
});
});
afterEach(function () {
afterEach(() => {
clock.restore();
});
it('wont update gasPrice in props before debounce', function () {
it('wont update gasPrice in props before debounce', () => {
const event = { target: { value: 1 } };
wrapper.find('input').at(0).simulate('change', event);
clock.tick(499);
assert.strictEqual(props.updateCustomGasPrice.callCount, 0);
expect(props.updateCustomGasPrice.callCount).toStrictEqual(0);
});
it('simulates onChange on gas price after debounce', function () {
it('simulates onChange on gas price after debounce', () => {
const event = { target: { value: 1 } };
wrapper.find('input').at(0).simulate('change', event);
clock.tick(500);
assert.strictEqual(props.updateCustomGasPrice.calledOnce, true);
assert.strictEqual(props.updateCustomGasPrice.calledWith(1), true);
expect(props.updateCustomGasPrice.calledOnce).toStrictEqual(true);
expect(props.updateCustomGasPrice.calledWith(1)).toStrictEqual(true);
});
it('wont update gasLimit in props before debounce', function () {
it('wont update gasLimit in props before debounce', () => {
const event = { target: { value: 21000 } };
wrapper.find('input').at(1).simulate('change', event);
clock.tick(499);
assert.strictEqual(props.updateCustomGasLimit.callCount, 0);
expect(props.updateCustomGasLimit.callCount).toStrictEqual(0);
});
it('simulates onChange on gas limit after debounce', function () {
it('simulates onChange on gas limit after debounce', () => {
const event = { target: { value: 21000 } };
wrapper.find('input').at(1).simulate('change', event);
clock.tick(500);
assert.strictEqual(props.updateCustomGasLimit.calledOnce, true);
assert.strictEqual(props.updateCustomGasLimit.calledWith(21000), true);
expect(props.updateCustomGasLimit.calledOnce).toStrictEqual(true);
expect(props.updateCustomGasLimit.calledWith(21000)).toStrictEqual(true);
});
it('errors when insufficientBalance under gas price and gas limit', function () {
it('errors when insufficientBalance under gas price and gas limit', () => {
wrapper.setProps({ insufficientBalance: true });
const renderError = wrapper.find(
'.advanced-gas-inputs__gas-edit-row__error-text',
);
assert.strictEqual(renderError.length, 2);
expect(renderError).toHaveLength(2);
assert.strictEqual(renderError.at(0).text(), 'insufficientBalance');
assert.strictEqual(renderError.at(1).text(), 'insufficientBalance');
expect(renderError.at(0).text()).toStrictEqual('insufficientBalance');
expect(renderError.at(1).text()).toStrictEqual('insufficientBalance');
});
it('errors zero gas price / speed up', function () {
it('errors zero gas price / speed up', () => {
wrapper.setProps({ isSpeedUp: true });
const renderError = wrapper.find(
'.advanced-gas-inputs__gas-edit-row__error-text',
);
assert.strictEqual(renderError.length, 2);
expect(renderError).toHaveLength(2);
assert.strictEqual(renderError.at(0).text(), 'zeroGasPriceOnSpeedUpError');
assert.strictEqual(
renderError.at(1).text(),
expect(renderError.at(0).text()).toStrictEqual(
'zeroGasPriceOnSpeedUpError',
);
expect(renderError.at(1).text()).toStrictEqual(
'gasLimitTooLowWithDynamicFee',
);
});
it('warns when custom gas price is too low', function () {
it('warns when custom gas price is too low', () => {
wrapper.setProps({ customPriceIsSafe: false });
const renderWarning = wrapper.find(
'.advanced-gas-inputs__gas-edit-row__warning-text',
);
assert.strictEqual(renderWarning.length, 1);
expect(renderWarning).toHaveLength(1);
assert.strictEqual(renderWarning.text(), 'gasPriceExtremelyLow');
expect(renderWarning.text()).toStrictEqual('gasPriceExtremelyLow');
});
it('errors when custom gas price is too excessive', function () {
it('errors when custom gas price is too excessive', () => {
wrapper.setProps({ customPriceIsExcessive: true });
const renderError = wrapper.find(
'.advanced-gas-inputs__gas-edit-row__error-text',
);
assert.strictEqual(renderError.length, 2);
assert.strictEqual(renderError.at(0).text(), 'gasPriceExcessiveInput');
expect(renderError).toHaveLength(2);
expect(renderError.at(0).text()).toStrictEqual('gasPriceExcessiveInput');
});
});

View File

@ -1,13 +1,12 @@
import assert from 'assert';
import React from 'react';
import sinon from 'sinon';
import shallow from '../../../../../../lib/shallow-with-context';
import AdvancedTabContent from './advanced-tab-content.component';
describe('AdvancedTabContent Component', function () {
describe('AdvancedTabContent Component', () => {
let wrapper;
beforeEach(function () {
beforeEach(() => {
const propsMethodSpies = {
updateCustomGasPrice: sinon.spy(),
updateCustomGasLimit: sinon.spy(),
@ -28,64 +27,65 @@ describe('AdvancedTabContent Component', function () {
);
});
afterEach(function () {
afterEach(() => {
sinon.restore();
});
describe('render()', function () {
it('should render the advanced-tab root node', function () {
assert(wrapper.hasClass('advanced-tab'));
describe('render()', () => {
it('should render the advanced-tab root node', () => {
expect(wrapper.hasClass('advanced-tab')).toStrictEqual(true);
});
it('should render the expected child of the advanced-tab div', function () {
it('should render the expected child of the advanced-tab div', () => {
const advancedTabChildren = wrapper.children();
assert.strictEqual(advancedTabChildren.length, 2);
expect(advancedTabChildren).toHaveLength(2);
assert(
expect(
advancedTabChildren
.at(0)
.hasClass('advanced-tab__transaction-data-summary'),
);
).toStrictEqual(true);
});
it('should call renderDataSummary with the expected params', function () {
it('should call renderDataSummary with the expected params', () => {
const renderDataSummaryArgs = AdvancedTabContent.prototype.renderDataSummary.getCall(
0,
).args;
assert.deepStrictEqual(renderDataSummaryArgs, ['$0.25']);
expect(renderDataSummaryArgs).toStrictEqual(['$0.25']);
});
});
describe('renderDataSummary()', function () {
describe('renderDataSummary()', () => {
let dataSummary;
beforeEach(function () {
beforeEach(() => {
dataSummary = shallow(
wrapper.instance().renderDataSummary('mockTotalFee'),
);
});
it('should render the transaction-data-summary root node', function () {
assert(dataSummary.hasClass('advanced-tab__transaction-data-summary'));
it('should render the transaction-data-summary root node', () => {
expect(
dataSummary.hasClass('advanced-tab__transaction-data-summary'),
).toStrictEqual(true);
});
it('should render titles of the data', function () {
it('should render titles of the data', () => {
const titlesNode = dataSummary.children().at(0);
assert(
expect(
titlesNode.hasClass('advanced-tab__transaction-data-summary__titles'),
);
assert.strictEqual(
titlesNode.children().at(0).text(),
).toStrictEqual(true);
expect(titlesNode.children().at(0).text()).toStrictEqual(
'newTransactionFee',
);
});
it('should render the data', function () {
it('should render the data', () => {
const dataNode = dataSummary.children().at(1);
assert(
expect(
dataNode.hasClass('advanced-tab__transaction-data-summary__container'),
);
assert.strictEqual(dataNode.children().at(0).text(), 'mockTotalFee');
).toStrictEqual(true);
expect(dataNode.children().at(0).text()).toStrictEqual('mockTotalFee');
});
});
});

View File

@ -1,4 +1,3 @@
import assert from 'assert';
import React from 'react';
import shallow from '../../../../../../lib/shallow-with-context';
import GasPriceButtonGroup from '../../gas-price-button-group';
@ -38,11 +37,11 @@ const mockGasPriceButtonGroupProps = {
showCheck: true,
};
describe('BasicTabContent Component', function () {
describe('render', function () {
describe('BasicTabContent Component', () => {
describe('render', () => {
let wrapper;
beforeEach(function () {
beforeEach(() => {
wrapper = shallow(
<BasicTabContent
gasPriceButtonGroupProps={mockGasPriceButtonGroupProps}
@ -50,20 +49,20 @@ describe('BasicTabContent Component', function () {
);
});
it('should have a title', function () {
assert(
it('should have a title', () => {
expect(
wrapper
.find('.basic-tab-content')
.childAt(0)
.hasClass('basic-tab-content__title'),
);
).toStrictEqual(true);
});
it('should render a GasPriceButtonGroup compenent', function () {
assert.strictEqual(wrapper.find(GasPriceButtonGroup).length, 1);
it('should render a GasPriceButtonGroup compenent', () => {
expect(wrapper.find(GasPriceButtonGroup)).toHaveLength(1);
});
it('should pass correct props to GasPriceButtonGroup', function () {
it('should pass correct props to GasPriceButtonGroup', () => {
const {
buttonDataLoading,
className,
@ -72,28 +71,24 @@ describe('BasicTabContent Component', function () {
noButtonActiveByDefault,
showCheck,
} = wrapper.find(GasPriceButtonGroup).props();
assert.strictEqual(wrapper.find(GasPriceButtonGroup).length, 1);
assert.strictEqual(
buttonDataLoading,
expect(wrapper.find(GasPriceButtonGroup)).toHaveLength(1);
expect(buttonDataLoading).toStrictEqual(
mockGasPriceButtonGroupProps.buttonDataLoading,
);
assert.strictEqual(className, mockGasPriceButtonGroupProps.className);
assert.strictEqual(
noButtonActiveByDefault,
expect(className).toStrictEqual(mockGasPriceButtonGroupProps.className);
expect(noButtonActiveByDefault).toStrictEqual(
mockGasPriceButtonGroupProps.noButtonActiveByDefault,
);
assert.strictEqual(showCheck, mockGasPriceButtonGroupProps.showCheck);
assert.deepStrictEqual(
gasButtonInfo,
expect(showCheck).toStrictEqual(mockGasPriceButtonGroupProps.showCheck);
expect(gasButtonInfo).toStrictEqual(
mockGasPriceButtonGroupProps.gasButtonInfo,
);
assert.strictEqual(
JSON.stringify(handleGasPriceSelection),
JSON.stringify(mockGasPriceButtonGroupProps.handleGasPriceSelection),
expect(handleGasPriceSelection).toStrictEqual(
mockGasPriceButtonGroupProps.handleGasPriceSelection,
);
});
it('should render a loading component instead of the GasPriceButtonGroup if gasPriceButtonGroupProps.loading is true', function () {
it('should render a loading component instead of the GasPriceButtonGroup if gasPriceButtonGroupProps.loading is true', () => {
wrapper.setProps({
gasPriceButtonGroupProps: {
...mockGasPriceButtonGroupProps,
@ -101,8 +96,8 @@ describe('BasicTabContent Component', function () {
},
});
assert.strictEqual(wrapper.find(GasPriceButtonGroup).length, 0);
assert.strictEqual(wrapper.find(Loading).length, 1);
expect(wrapper.find(GasPriceButtonGroup)).toHaveLength(0);
expect(wrapper.find(Loading)).toHaveLength(1);
});
});
});

View File

@ -1,4 +1,3 @@
import assert from 'assert';
import React from 'react';
import sinon from 'sinon';
import shallow from '../../../../../lib/shallow-with-context';
@ -60,10 +59,10 @@ const mockInfoRowProps = {
};
const GP = GasModalPageContainer.prototype;
describe('GasModalPageContainer Component', function () {
describe('GasModalPageContainer Component', () => {
let wrapper;
beforeEach(function () {
beforeEach(() => {
wrapper = shallow(
<GasModalPageContainer
cancelAndClose={propsMethodSpies.cancelAndClose}
@ -81,41 +80,45 @@ describe('GasModalPageContainer Component', function () {
);
});
afterEach(function () {
afterEach(() => {
propsMethodSpies.cancelAndClose.resetHistory();
});
describe('componentDidMount', function () {
it('should call props.fetchBasicGasEstimates', function () {
describe('componentDidMount', () => {
it('should call props.fetchBasicGasEstimates', () => {
propsMethodSpies.fetchBasicGasEstimates.resetHistory();
assert.strictEqual(propsMethodSpies.fetchBasicGasEstimates.callCount, 0);
expect(propsMethodSpies.fetchBasicGasEstimates.callCount).toStrictEqual(
0,
);
wrapper.instance().componentDidMount();
assert.strictEqual(propsMethodSpies.fetchBasicGasEstimates.callCount, 1);
expect(propsMethodSpies.fetchBasicGasEstimates.callCount).toStrictEqual(
1,
);
});
});
describe('render', function () {
it('should render a PageContainer compenent', function () {
assert.strictEqual(wrapper.find(PageContainer).length, 1);
describe('render', () => {
it('should render a PageContainer compenent', () => {
expect(wrapper.find(PageContainer)).toHaveLength(1);
});
it('should pass correct props to PageContainer', function () {
it('should pass correct props to PageContainer', () => {
const { title, subtitle, disabled } = wrapper.find(PageContainer).props();
assert.strictEqual(title, 'customGas');
assert.strictEqual(subtitle, 'customGasSubTitle');
assert.strictEqual(disabled, false);
expect(title).toStrictEqual('customGas');
expect(subtitle).toStrictEqual('customGasSubTitle');
expect(disabled).toStrictEqual(false);
});
it('should pass the correct onCancel and onClose methods to PageContainer', function () {
it('should pass the correct onCancel and onClose methods to PageContainer', () => {
const { onCancel, onClose } = wrapper.find(PageContainer).props();
assert.strictEqual(propsMethodSpies.cancelAndClose.callCount, 0);
expect(propsMethodSpies.cancelAndClose.callCount).toStrictEqual(0);
onCancel();
assert.strictEqual(propsMethodSpies.cancelAndClose.callCount, 1);
expect(propsMethodSpies.cancelAndClose.callCount).toStrictEqual(1);
onClose();
assert.strictEqual(propsMethodSpies.cancelAndClose.callCount, 2);
expect(propsMethodSpies.cancelAndClose.callCount).toStrictEqual(2);
});
it('should pass the correct renderTabs property to PageContainer', function () {
it('should pass the correct renderTabs property to PageContainer', () => {
sinon.stub(GP, 'renderTabs').returns('mockTabs');
const renderTabsWrapperTester = shallow(
<GasModalPageContainer
@ -127,59 +130,57 @@ describe('GasModalPageContainer Component', function () {
const { tabsComponent } = renderTabsWrapperTester
.find(PageContainer)
.props();
assert.strictEqual(tabsComponent, 'mockTabs');
expect(tabsComponent).toStrictEqual('mockTabs');
GasModalPageContainer.prototype.renderTabs.restore();
});
});
describe('renderTabs', function () {
beforeEach(function () {
describe('renderTabs', () => {
beforeEach(() => {
sinon.spy(GP, 'renderBasicTabContent');
sinon.spy(GP, 'renderAdvancedTabContent');
sinon.spy(GP, 'renderInfoRows');
});
afterEach(function () {
afterEach(() => {
GP.renderBasicTabContent.restore();
GP.renderAdvancedTabContent.restore();
GP.renderInfoRows.restore();
});
it('should render a Tabs component with "Basic" and "Advanced" tabs', function () {
it('should render a Tabs component with "Basic" and "Advanced" tabs', () => {
const renderTabsResult = wrapper.instance().renderTabs();
const renderedTabs = shallow(renderTabsResult);
assert.strictEqual(renderedTabs.props().className, 'tabs');
expect(renderedTabs.props().className).toStrictEqual('tabs');
const tabs = renderedTabs.find(Tab);
assert.strictEqual(tabs.length, 2);
expect(tabs).toHaveLength(2);
assert.strictEqual(tabs.at(0).props().name, 'basic');
assert.strictEqual(tabs.at(1).props().name, 'advanced');
expect(tabs.at(0).props().name).toStrictEqual('basic');
expect(tabs.at(1).props().name).toStrictEqual('advanced');
assert.strictEqual(
tabs.at(0).childAt(0).props().className,
expect(tabs.at(0).childAt(0).props().className).toStrictEqual(
'gas-modal-content',
);
assert.strictEqual(
tabs.at(1).childAt(0).props().className,
expect(tabs.at(1).childAt(0).props().className).toStrictEqual(
'gas-modal-content',
);
});
it('should call renderInfoRows with the expected props', function () {
assert.strictEqual(GP.renderInfoRows.callCount, 0);
it('should call renderInfoRows with the expected props', () => {
expect(GP.renderInfoRows.callCount).toStrictEqual(0);
wrapper.instance().renderTabs();
assert.strictEqual(GP.renderInfoRows.callCount, 2);
expect(GP.renderInfoRows.callCount).toStrictEqual(2);
assert.deepStrictEqual(GP.renderInfoRows.getCall(0).args, [
expect(GP.renderInfoRows.getCall(0).args).toStrictEqual([
'mockNewTotalFiat',
'mockNewTotalEth',
'mockSendAmount',
'mockTransactionFee',
]);
assert.deepStrictEqual(GP.renderInfoRows.getCall(1).args, [
expect(GP.renderInfoRows.getCall(1).args).toStrictEqual([
'mockNewTotalFiat',
'mockNewTotalEth',
'mockSendAmount',
@ -187,7 +188,7 @@ describe('GasModalPageContainer Component', function () {
]);
});
it('should not render the basic tab if hideBasic is true', function () {
it('should not render the basic tab if hideBasic is true', () => {
wrapper = shallow(
<GasModalPageContainer
cancelAndClose={propsMethodSpies.cancelAndClose}
@ -208,26 +209,25 @@ describe('GasModalPageContainer Component', function () {
const renderedTabs = shallow(renderTabsResult);
const tabs = renderedTabs.find(Tab);
assert.strictEqual(tabs.length, 1);
assert.strictEqual(tabs.at(0).props().name, 'advanced');
expect(tabs).toHaveLength(1);
expect(tabs.at(0).props().name).toStrictEqual('advanced');
});
});
describe('renderBasicTabContent', function () {
it('should render', function () {
describe('renderBasicTabContent', () => {
it('should render', () => {
const renderBasicTabContentResult = wrapper
.instance()
.renderBasicTabContent(mockGasPriceButtonGroupProps);
assert.deepStrictEqual(
expect(
renderBasicTabContentResult.props.gasPriceButtonGroupProps,
mockGasPriceButtonGroupProps,
);
).toStrictEqual(mockGasPriceButtonGroupProps);
});
});
describe('renderInfoRows', function () {
it('should render the info rows with the passed data', function () {
describe('renderInfoRows', () => {
it('should render the info rows with the passed data', () => {
const baseClassName = 'gas-modal-content__info-row';
const renderedInfoRowsContainer = shallow(
wrapper
@ -240,32 +240,35 @@ describe('GasModalPageContainer Component', function () {
),
);
assert(renderedInfoRowsContainer.childAt(0).hasClass(baseClassName));
expect(
renderedInfoRowsContainer.childAt(0).hasClass(baseClassName),
).toStrictEqual(true);
const renderedInfoRows = renderedInfoRowsContainer.childAt(0).children();
assert.strictEqual(renderedInfoRows.length, 4);
assert(renderedInfoRows.at(0).hasClass(`${baseClassName}__send-info`));
assert(
expect(renderedInfoRows).toHaveLength(4);
expect(
renderedInfoRows.at(0).hasClass(`${baseClassName}__send-info`),
).toStrictEqual(true);
expect(
renderedInfoRows.at(1).hasClass(`${baseClassName}__transaction-info`),
);
assert(renderedInfoRows.at(2).hasClass(`${baseClassName}__total-info`));
assert(
).toStrictEqual(true);
expect(
renderedInfoRows.at(2).hasClass(`${baseClassName}__total-info`),
).toStrictEqual(true);
expect(
renderedInfoRows.at(3).hasClass(`${baseClassName}__fiat-total-info`),
);
).toStrictEqual(true);
assert.strictEqual(
renderedInfoRows.at(0).text(),
expect(renderedInfoRows.at(0).text()).toStrictEqual(
'sendAmount mockSendAmount',
);
assert.strictEqual(
renderedInfoRows.at(1).text(),
expect(renderedInfoRows.at(1).text()).toStrictEqual(
'transactionFee mockTransactionFee',
);
assert.strictEqual(
renderedInfoRows.at(2).text(),
expect(renderedInfoRows.at(2).text()).toStrictEqual(
'newTotal mockNewTotalEth',
);
assert.strictEqual(renderedInfoRows.at(3).text(), 'mockNewTotalFiat');
expect(renderedInfoRows.at(3).text()).toStrictEqual('mockNewTotalFiat');
});
});
});

View File

@ -1,145 +1,155 @@
import assert from 'assert';
import proxyquire from 'proxyquire';
import sinon from 'sinon';
import { hideModal, setGasLimit, setGasPrice } from '../../../../store/actions';
import {
setCustomGasPrice,
setCustomGasLimit,
resetCustomData,
} from '../../../../ducks/gas/gas.duck';
import { hideGasButtonGroup } from '../../../../ducks/send/send.duck';
let mapDispatchToProps;
let mergeProps;
const actionSpies = {
hideModal: sinon.spy(),
setGasLimit: sinon.spy(),
setGasPrice: sinon.spy(),
};
const gasActionSpies = {
setCustomGasPrice: sinon.spy(),
setCustomGasLimit: sinon.spy(),
resetCustomData: sinon.spy(),
};
const sendActionSpies = {
hideGasButtonGroup: sinon.spy(),
};
proxyquire('./gas-modal-page-container.container.js', {
'react-redux': {
connect: (_, md, mp) => {
mapDispatchToProps = md;
mergeProps = mp;
return () => ({});
},
jest.mock('react-redux', () => ({
connect: (_, md, mp) => {
mapDispatchToProps = md;
mergeProps = mp;
return () => ({});
},
'../../../../selectors': {
getBasicGasEstimateLoadingStatus: (s) =>
`mockBasicGasEstimateLoadingStatus:${Object.keys(s).length}`,
getRenderableBasicEstimateData: (s) =>
`mockRenderableBasicEstimateData:${Object.keys(s).length}`,
getDefaultActiveButtonIndex: (a, b) => a + b,
getCurrentEthBalance: (state) => state.metamask.balance || '0x0',
getSendToken: () => null,
getTokenBalance: (state) => state.metamask.send.tokenBalance || '0x0',
},
'../../../../store/actions': actionSpies,
'../../../../ducks/gas/gas.duck': gasActionSpies,
'../../../../ducks/send/send.duck': sendActionSpies,
});
}));
describe('gas-modal-page-container container', function () {
describe('mapDispatchToProps()', function () {
jest.mock('../../../../../app/selectors', () => ({
getBasicGasEstimateLoadingStatus: (s) =>
`mockBasicGasEstimateLoadingStatus:${Object.keys(s).length}`,
getRenderableBasicEstimateData: (s) =>
`mockRenderableBasicEstimateData:${Object.keys(s).length}`,
getDefaultActiveButtonIndex: (a, b) => a + b,
getCurrentEthBalance: (state) => state.metamask.balance || '0x0',
getSendToken: () => null,
getTokenBalance: (state) => state.metamask.send.tokenBalance || '0x0',
getCustomGasPrice: (state) => state.gas.customData.price || '0x0',
getCustomGasLimit: (state) => state.gas.customData.limit || '0x0',
getCurrentCurrency: jest.fn().mockReturnValue('usd'),
conversionRateSelector: jest.fn().mockReturnValue(50),
getSendMaxModeState: jest.fn().mockReturnValue(false),
getPreferences: jest.fn(() => ({
showFiatInTestnets: false,
})),
getIsMainnet: jest.fn().mockReturnValue(false),
isCustomPriceSafe: jest.fn().mockReturnValue(true),
}));
jest.mock('../../../../../app/store/actions', () => ({
hideModal: jest.fn(),
setGasLimit: jest.fn(),
setGasPrice: jest.fn(),
updateTransaction: jest.fn(),
}));
jest.mock('../../../../../app/ducks/gas/gas.duck', () => ({
setCustomGasPrice: jest.fn(),
setCustomGasLimit: jest.fn(),
resetCustomData: jest.fn(),
}));
jest.mock('../../../../../app/ducks/send/send.duck', () => ({
hideGasButtonGroup: jest.fn(),
}));
require('./gas-modal-page-container.container');
describe('gas-modal-page-container container', () => {
describe('mapDispatchToProps()', () => {
let dispatchSpy;
let mapDispatchToPropsObject;
beforeEach(function () {
beforeEach(() => {
dispatchSpy = sinon.spy();
mapDispatchToPropsObject = mapDispatchToProps(dispatchSpy);
});
afterEach(function () {
actionSpies.hideModal.resetHistory();
gasActionSpies.setCustomGasPrice.resetHistory();
gasActionSpies.setCustomGasLimit.resetHistory();
afterEach(() => {
dispatchSpy.resetHistory();
});
describe('hideGasButtonGroup()', function () {
it('should dispatch a hideGasButtonGroup action', function () {
describe('hideGasButtonGroup()', () => {
it('should dispatch a hideGasButtonGroup action', () => {
mapDispatchToPropsObject.hideGasButtonGroup();
assert(dispatchSpy.calledOnce);
assert(sendActionSpies.hideGasButtonGroup.calledOnce);
expect(dispatchSpy.calledOnce).toStrictEqual(true);
expect(hideGasButtonGroup).toHaveBeenCalled();
});
});
describe('cancelAndClose()', function () {
it('should dispatch a hideModal action', function () {
describe('cancelAndClose()', () => {
it('should dispatch a hideModal action', () => {
mapDispatchToPropsObject.cancelAndClose();
assert(dispatchSpy.calledTwice);
assert(actionSpies.hideModal.calledOnce);
assert(gasActionSpies.resetCustomData.calledOnce);
expect(dispatchSpy.calledTwice).toStrictEqual(true);
expect(hideModal).toHaveBeenCalled();
expect(resetCustomData).toHaveBeenCalled();
});
});
describe('updateCustomGasPrice()', function () {
it('should dispatch a setCustomGasPrice action with the arg passed to updateCustomGasPrice hex prefixed', function () {
describe('updateCustomGasPrice()', () => {
it('should dispatch a setCustomGasPrice action with the arg passed to updateCustomGasPrice hex prefixed', () => {
mapDispatchToPropsObject.updateCustomGasPrice('ffff');
assert(dispatchSpy.calledOnce);
assert(gasActionSpies.setCustomGasPrice.calledOnce);
assert.strictEqual(
gasActionSpies.setCustomGasPrice.getCall(0).args[0],
'0xffff',
);
expect(dispatchSpy.calledOnce).toStrictEqual(true);
expect(setCustomGasPrice).toHaveBeenCalled();
expect(setCustomGasPrice).toHaveBeenCalledWith('0xffff');
// expect(
// setCustomGasPrice.getCall(0).args[0],
// '0xffff',
// );
});
it('should dispatch a setCustomGasPrice action', function () {
it('should dispatch a setCustomGasPrice action', () => {
mapDispatchToPropsObject.updateCustomGasPrice('0xffff');
assert(dispatchSpy.calledOnce);
assert(gasActionSpies.setCustomGasPrice.calledOnce);
assert.strictEqual(
gasActionSpies.setCustomGasPrice.getCall(0).args[0],
'0xffff',
);
expect(dispatchSpy.calledOnce).toStrictEqual(true);
expect(setCustomGasPrice).toHaveBeenCalled();
expect(setCustomGasPrice).toHaveBeenCalledWith('0xffff');
});
});
describe('updateCustomGasLimit()', function () {
it('should dispatch a setCustomGasLimit action', function () {
describe('updateCustomGasLimit()', () => {
it('should dispatch a setCustomGasLimit action', () => {
mapDispatchToPropsObject.updateCustomGasLimit('0x10');
assert(dispatchSpy.calledOnce);
assert(gasActionSpies.setCustomGasLimit.calledOnce);
assert.strictEqual(
gasActionSpies.setCustomGasLimit.getCall(0).args[0],
'0x10',
);
expect(dispatchSpy.calledOnce).toStrictEqual(true);
expect(setCustomGasLimit).toHaveBeenCalled();
expect(setCustomGasLimit).toHaveBeenCalledWith('0x10');
});
});
describe('setGasData()', function () {
it('should dispatch a setGasPrice and setGasLimit action with the correct props', function () {
describe('setGasData()', () => {
it('should dispatch a setGasPrice and setGasLimit action with the correct props', () => {
mapDispatchToPropsObject.setGasData('ffff', 'aaaa');
assert(dispatchSpy.calledTwice);
assert(actionSpies.setGasPrice.calledOnce);
assert(actionSpies.setGasLimit.calledOnce);
assert.strictEqual(actionSpies.setGasLimit.getCall(0).args[0], 'ffff');
assert.strictEqual(actionSpies.setGasPrice.getCall(0).args[0], 'aaaa');
expect(dispatchSpy.calledTwice).toStrictEqual(true);
expect(setGasPrice).toHaveBeenCalled();
expect(setGasLimit).toHaveBeenCalled();
expect(setGasLimit).toHaveBeenCalledWith('ffff');
expect(setGasPrice).toHaveBeenCalledWith('aaaa');
});
});
describe('updateConfirmTxGasAndCalculate()', function () {
it('should dispatch a updateGasAndCalculate action with the correct props', function () {
describe('updateConfirmTxGasAndCalculate()', () => {
it('should dispatch a updateGasAndCalculate action with the correct props', () => {
mapDispatchToPropsObject.updateConfirmTxGasAndCalculate('ffff', 'aaaa');
assert.strictEqual(dispatchSpy.callCount, 3);
assert(actionSpies.setGasPrice.calledOnce);
assert(actionSpies.setGasLimit.calledOnce);
assert.strictEqual(actionSpies.setGasLimit.getCall(0).args[0], 'ffff');
assert.strictEqual(actionSpies.setGasPrice.getCall(0).args[0], 'aaaa');
expect(dispatchSpy.callCount).toStrictEqual(3);
expect(setCustomGasPrice).toHaveBeenCalled();
expect(setCustomGasLimit).toHaveBeenCalled();
expect(setCustomGasLimit).toHaveBeenCalledWith('0xffff');
expect(setCustomGasPrice).toHaveBeenCalledWith('0xaaaa');
});
});
});
describe('mergeProps', function () {
describe('mergeProps', () => {
let stateProps;
let dispatchProps;
let ownProps;
beforeEach(function () {
beforeEach(() => {
stateProps = {
gasPriceButtonGroupProps: {
someGasPriceButtonGroupProp: 'foo',
@ -163,113 +173,95 @@ describe('gas-modal-page-container container', function () {
ownProps = { someOwnProp: 123 };
});
afterEach(function () {
dispatchProps.updateCustomGasPrice.resetHistory();
dispatchProps.hideGasButtonGroup.resetHistory();
dispatchProps.setGasData.resetHistory();
dispatchProps.updateConfirmTxGasAndCalculate.resetHistory();
dispatchProps.someOtherDispatchProp.resetHistory();
dispatchProps.createSpeedUpTransaction.resetHistory();
dispatchProps.hideSidebar.resetHistory();
dispatchProps.hideModal.resetHistory();
});
it('should return the expected props when isConfirm is true', function () {
it('should return the expected props when isConfirm is true', () => {
const result = mergeProps(stateProps, dispatchProps, ownProps);
assert.strictEqual(result.isConfirm, true);
assert.strictEqual(result.someOtherStateProp, 'baz');
assert.strictEqual(
expect(result.isConfirm).toStrictEqual(true);
expect(result.someOtherStateProp).toStrictEqual('baz');
expect(
result.gasPriceButtonGroupProps.someGasPriceButtonGroupProp,
'foo',
);
assert.strictEqual(
).toStrictEqual('foo');
expect(
result.gasPriceButtonGroupProps.anotherGasPriceButtonGroupProp,
'bar',
);
assert.strictEqual(result.someOwnProp, 123);
).toStrictEqual('bar');
expect(result.someOwnProp).toStrictEqual(123);
assert.strictEqual(
expect(
dispatchProps.updateConfirmTxGasAndCalculate.callCount,
0,
);
assert.strictEqual(dispatchProps.setGasData.callCount, 0);
assert.strictEqual(dispatchProps.hideGasButtonGroup.callCount, 0);
assert.strictEqual(dispatchProps.hideModal.callCount, 0);
).toStrictEqual(0);
expect(dispatchProps.setGasData.callCount).toStrictEqual(0);
expect(dispatchProps.hideGasButtonGroup.callCount).toStrictEqual(0);
expect(dispatchProps.hideModal.callCount).toStrictEqual(0);
result.onSubmit();
assert.strictEqual(
expect(
dispatchProps.updateConfirmTxGasAndCalculate.callCount,
1,
);
assert.strictEqual(dispatchProps.setGasData.callCount, 0);
assert.strictEqual(dispatchProps.hideGasButtonGroup.callCount, 0);
assert.strictEqual(dispatchProps.hideModal.callCount, 1);
).toStrictEqual(1);
expect(dispatchProps.setGasData.callCount).toStrictEqual(0);
expect(dispatchProps.hideGasButtonGroup.callCount).toStrictEqual(0);
expect(dispatchProps.hideModal.callCount).toStrictEqual(1);
assert.strictEqual(dispatchProps.updateCustomGasPrice.callCount, 0);
expect(dispatchProps.updateCustomGasPrice.callCount).toStrictEqual(0);
result.gasPriceButtonGroupProps.handleGasPriceSelection({
gasPrice: '0x0',
});
assert.strictEqual(dispatchProps.updateCustomGasPrice.callCount, 1);
expect(dispatchProps.updateCustomGasPrice.callCount).toStrictEqual(1);
assert.strictEqual(dispatchProps.someOtherDispatchProp.callCount, 0);
expect(dispatchProps.someOtherDispatchProp.callCount).toStrictEqual(0);
result.someOtherDispatchProp();
assert.strictEqual(dispatchProps.someOtherDispatchProp.callCount, 1);
expect(dispatchProps.someOtherDispatchProp.callCount).toStrictEqual(1);
});
it('should return the expected props when isConfirm is false', function () {
it('should return the expected props when isConfirm is false', () => {
const result = mergeProps(
{ ...stateProps, isConfirm: false },
dispatchProps,
ownProps,
);
assert.strictEqual(result.isConfirm, false);
assert.strictEqual(result.someOtherStateProp, 'baz');
assert.strictEqual(
expect(result.isConfirm).toStrictEqual(false);
expect(result.someOtherStateProp).toStrictEqual('baz');
expect(
result.gasPriceButtonGroupProps.someGasPriceButtonGroupProp,
'foo',
);
assert.strictEqual(
).toStrictEqual('foo');
expect(
result.gasPriceButtonGroupProps.anotherGasPriceButtonGroupProp,
'bar',
);
assert.strictEqual(result.someOwnProp, 123);
).toStrictEqual('bar');
expect(result.someOwnProp).toStrictEqual(123);
assert.strictEqual(
expect(
dispatchProps.updateConfirmTxGasAndCalculate.callCount,
0,
);
assert.strictEqual(dispatchProps.setGasData.callCount, 0);
assert.strictEqual(dispatchProps.hideGasButtonGroup.callCount, 0);
assert.strictEqual(dispatchProps.cancelAndClose.callCount, 0);
).toStrictEqual(0);
expect(dispatchProps.setGasData.callCount).toStrictEqual(0);
expect(dispatchProps.hideGasButtonGroup.callCount).toStrictEqual(0);
expect(dispatchProps.cancelAndClose.callCount).toStrictEqual(0);
result.onSubmit('mockNewLimit', 'mockNewPrice');
assert.strictEqual(
expect(
dispatchProps.updateConfirmTxGasAndCalculate.callCount,
0,
);
assert.strictEqual(dispatchProps.setGasData.callCount, 1);
assert.deepStrictEqual(dispatchProps.setGasData.getCall(0).args, [
).toStrictEqual(0);
expect(dispatchProps.setGasData.callCount).toStrictEqual(1);
expect(dispatchProps.setGasData.getCall(0).args).toStrictEqual([
'mockNewLimit',
'mockNewPrice',
]);
assert.strictEqual(dispatchProps.hideGasButtonGroup.callCount, 1);
assert.strictEqual(dispatchProps.cancelAndClose.callCount, 1);
expect(dispatchProps.hideGasButtonGroup.callCount).toStrictEqual(1);
expect(dispatchProps.cancelAndClose.callCount).toStrictEqual(1);
assert.strictEqual(dispatchProps.updateCustomGasPrice.callCount, 0);
expect(dispatchProps.updateCustomGasPrice.callCount).toStrictEqual(0);
result.gasPriceButtonGroupProps.handleGasPriceSelection({
gasPrice: '0x0',
});
assert.strictEqual(dispatchProps.updateCustomGasPrice.callCount, 1);
expect(dispatchProps.updateCustomGasPrice.callCount).toStrictEqual(1);
assert.strictEqual(dispatchProps.someOtherDispatchProp.callCount, 0);
expect(dispatchProps.someOtherDispatchProp.callCount).toStrictEqual(0);
result.someOtherDispatchProp();
assert.strictEqual(dispatchProps.someOtherDispatchProp.callCount, 1);
expect(dispatchProps.someOtherDispatchProp.callCount).toStrictEqual(1);
});
it('should dispatch the expected actions from obSubmit when isConfirm is false and isSpeedUp is true', function () {
it('should dispatch the expected actions from obSubmit when isConfirm is false and isSpeedUp is true', () => {
const result = mergeProps(
{ ...stateProps, isSpeedUp: true, isConfirm: false },
dispatchProps,
@ -278,16 +270,15 @@ describe('gas-modal-page-container container', function () {
result.onSubmit();
assert.strictEqual(
expect(
dispatchProps.updateConfirmTxGasAndCalculate.callCount,
0,
);
assert.strictEqual(dispatchProps.setGasData.callCount, 0);
assert.strictEqual(dispatchProps.hideGasButtonGroup.callCount, 0);
assert.strictEqual(dispatchProps.cancelAndClose.callCount, 1);
).toStrictEqual(0);
expect(dispatchProps.setGasData.callCount).toStrictEqual(0);
expect(dispatchProps.hideGasButtonGroup.callCount).toStrictEqual(0);
expect(dispatchProps.cancelAndClose.callCount).toStrictEqual(1);
assert.strictEqual(dispatchProps.createSpeedUpTransaction.callCount, 1);
assert.strictEqual(dispatchProps.hideSidebar.callCount, 1);
expect(dispatchProps.createSpeedUpTransaction.callCount).toStrictEqual(1);
expect(dispatchProps.hideSidebar.callCount).toStrictEqual(1);
});
});
});

View File

@ -1,4 +1,3 @@
import assert from 'assert';
import React from 'react';
import sinon from 'sinon';
import shallow from '../../../../../lib/shallow-with-context';
@ -7,12 +6,12 @@ import { GAS_ESTIMATE_TYPES } from '../../../../helpers/constants/common';
import ButtonGroup from '../../../ui/button-group';
import GasPriceButtonGroup from './gas-price-button-group.component';
describe('GasPriceButtonGroup Component', function () {
describe('GasPriceButtonGroup Component', () => {
let mockButtonPropsAndFlags;
let mockGasPriceButtonGroupProps;
let wrapper;
beforeEach(function () {
beforeEach(() => {
mockGasPriceButtonGroupProps = {
buttonDataLoading: false,
className: 'gas-price-button-group',
@ -60,59 +59,59 @@ describe('GasPriceButtonGroup Component', function () {
);
});
afterEach(function () {
afterEach(() => {
sinon.restore();
});
describe('render', function () {
it('should render a ButtonGroup', function () {
assert(wrapper.is(ButtonGroup));
describe('render', () => {
it('should render a ButtonGroup', () => {
expect(wrapper.is(ButtonGroup)).toStrictEqual(true);
});
it('should render the correct props on the ButtonGroup', function () {
it('should render the correct props on the ButtonGroup', () => {
const {
className,
defaultActiveButtonIndex,
noButtonActiveByDefault,
} = wrapper.props();
assert.strictEqual(className, 'gas-price-button-group');
assert.strictEqual(defaultActiveButtonIndex, 2);
assert.strictEqual(noButtonActiveByDefault, true);
expect(className).toStrictEqual('gas-price-button-group');
expect(defaultActiveButtonIndex).toStrictEqual(2);
expect(noButtonActiveByDefault).toStrictEqual(true);
});
function renderButtonArgsTest(i, mockPropsAndFlags) {
assert.deepStrictEqual(
expect(
GasPriceButtonGroup.prototype.renderButton.getCall(i).args,
[
{ ...mockGasPriceButtonGroupProps.gasButtonInfo[i] },
mockPropsAndFlags,
i,
],
);
).toStrictEqual([
{ ...mockGasPriceButtonGroupProps.gasButtonInfo[i] },
mockPropsAndFlags,
i,
]);
}
it('should call this.renderButton 3 times, with the correct args', function () {
assert.strictEqual(
it('should call this.renderButton 3 times, with the correct args', () => {
expect(
GasPriceButtonGroup.prototype.renderButton.callCount,
3,
);
).toStrictEqual(3);
renderButtonArgsTest(0, mockButtonPropsAndFlags);
renderButtonArgsTest(1, mockButtonPropsAndFlags);
renderButtonArgsTest(2, mockButtonPropsAndFlags);
});
it('should show loading if buttonDataLoading', function () {
it('should show loading if buttonDataLoading', () => {
wrapper.setProps({ buttonDataLoading: true });
assert(wrapper.is('div'));
assert(wrapper.hasClass('gas-price-button-group__loading-container'));
assert.strictEqual(wrapper.text(), 'loading');
expect(wrapper.is('div')).toStrictEqual(true);
expect(
wrapper.hasClass('gas-price-button-group__loading-container'),
).toStrictEqual(true);
expect(wrapper.text()).toStrictEqual('loading');
});
});
describe('renderButton', function () {
describe('renderButton', () => {
let wrappedRenderButtonResult;
beforeEach(function () {
beforeEach(() => {
GasPriceButtonGroup.prototype.renderButtonContent.resetHistory();
const renderButtonResult = wrapper
.instance()
@ -123,38 +122,33 @@ describe('GasPriceButtonGroup Component', function () {
wrappedRenderButtonResult = shallow(renderButtonResult);
});
it('should render a button', function () {
assert.strictEqual(wrappedRenderButtonResult.type(), 'button');
it('should render a button', () => {
expect(wrappedRenderButtonResult.type()).toStrictEqual('button');
});
it('should call the correct method when clicked', function () {
assert.strictEqual(
it('should call the correct method when clicked', () => {
expect(
mockGasPriceButtonGroupProps.handleGasPriceSelection.callCount,
0,
);
).toStrictEqual(0);
wrappedRenderButtonResult.props().onClick();
assert.strictEqual(
expect(
mockGasPriceButtonGroupProps.handleGasPriceSelection.callCount,
1,
);
assert.deepStrictEqual(
).toStrictEqual(1);
expect(
mockGasPriceButtonGroupProps.handleGasPriceSelection.getCall(0).args,
[
{
gasPrice:
mockGasPriceButtonGroupProps.gasButtonInfo[0].priceInHexWei,
gasEstimateType:
mockGasPriceButtonGroupProps.gasButtonInfo[0].gasEstimateType,
},
],
);
).toStrictEqual([
{
gasPrice: mockGasPriceButtonGroupProps.gasButtonInfo[0].priceInHexWei,
gasEstimateType:
mockGasPriceButtonGroupProps.gasButtonInfo[0].gasEstimateType,
},
]);
});
it('should call this.renderButtonContent with the correct args', function () {
assert.strictEqual(
it('should call this.renderButtonContent with the correct args', () => {
expect(
GasPriceButtonGroup.prototype.renderButtonContent.callCount,
1,
);
).toStrictEqual(1);
const {
feeInPrimaryCurrency,
feeInSecondaryCurrency,
@ -162,26 +156,25 @@ describe('GasPriceButtonGroup Component', function () {
gasEstimateType,
} = mockGasPriceButtonGroupProps.gasButtonInfo[0];
const { showCheck, className } = mockGasPriceButtonGroupProps;
assert.deepStrictEqual(
expect(
GasPriceButtonGroup.prototype.renderButtonContent.getCall(0).args,
[
{
gasEstimateType,
feeInPrimaryCurrency,
feeInSecondaryCurrency,
timeEstimate,
},
{
showCheck,
className,
},
],
);
).toStrictEqual([
{
gasEstimateType,
feeInPrimaryCurrency,
feeInSecondaryCurrency,
timeEstimate,
},
{
showCheck,
className,
},
]);
});
});
describe('renderButtonContent', function () {
it('should render a label if passed a gasEstimateType', function () {
describe('renderButtonContent', () => {
it('should render a label if passed a gasEstimateType', () => {
const renderButtonContentResult = wrapper.instance().renderButtonContent(
{
gasEstimateType: 'SLOW',
@ -193,17 +186,15 @@ describe('GasPriceButtonGroup Component', function () {
const wrappedRenderButtonContentResult = shallow(
renderButtonContentResult,
);
assert.strictEqual(
wrappedRenderButtonContentResult.childAt(0).children().length,
1,
);
assert.strictEqual(
expect(
wrappedRenderButtonContentResult.childAt(0).children(),
).toHaveLength(1);
expect(
wrappedRenderButtonContentResult.find('.someClass__label').text(),
'slow',
);
).toStrictEqual('slow');
});
it('should render a feeInPrimaryCurrency if passed a feeInPrimaryCurrency', function () {
it('should render a feeInPrimaryCurrency if passed a feeInPrimaryCurrency', () => {
const renderButtonContentResult = GasPriceButtonGroup.prototype.renderButtonContent(
{
feeInPrimaryCurrency: 'mockFeeInPrimaryCurrency',
@ -215,19 +206,17 @@ describe('GasPriceButtonGroup Component', function () {
const wrappedRenderButtonContentResult = shallow(
renderButtonContentResult,
);
assert.strictEqual(
wrappedRenderButtonContentResult.childAt(0).children().length,
1,
);
assert.strictEqual(
expect(
wrappedRenderButtonContentResult.childAt(0).children(),
).toHaveLength(1);
expect(
wrappedRenderButtonContentResult
.find('.someClass__primary-currency')
.text(),
'mockFeeInPrimaryCurrency',
);
).toStrictEqual('mockFeeInPrimaryCurrency');
});
it('should render a feeInSecondaryCurrency if passed a feeInSecondaryCurrency', function () {
it('should render a feeInSecondaryCurrency if passed a feeInSecondaryCurrency', () => {
const renderButtonContentResult = GasPriceButtonGroup.prototype.renderButtonContent(
{
feeInSecondaryCurrency: 'mockFeeInSecondaryCurrency',
@ -239,19 +228,17 @@ describe('GasPriceButtonGroup Component', function () {
const wrappedRenderButtonContentResult = shallow(
renderButtonContentResult,
);
assert.strictEqual(
wrappedRenderButtonContentResult.childAt(0).children().length,
1,
);
assert.strictEqual(
expect(
wrappedRenderButtonContentResult.childAt(0).children(),
).toHaveLength(1);
expect(
wrappedRenderButtonContentResult
.find('.someClass__secondary-currency')
.text(),
'mockFeeInSecondaryCurrency',
);
).toStrictEqual('mockFeeInSecondaryCurrency');
});
it('should render a timeEstimate if passed a timeEstimate', function () {
it('should render a timeEstimate if passed a timeEstimate', () => {
const renderButtonContentResult = GasPriceButtonGroup.prototype.renderButtonContent(
{
timeEstimate: 'mockTimeEstimate',
@ -263,19 +250,17 @@ describe('GasPriceButtonGroup Component', function () {
const wrappedRenderButtonContentResult = shallow(
renderButtonContentResult,
);
assert.strictEqual(
wrappedRenderButtonContentResult.childAt(0).children().length,
1,
);
assert.strictEqual(
expect(
wrappedRenderButtonContentResult.childAt(0).children(),
).toHaveLength(1);
expect(
wrappedRenderButtonContentResult
.find('.someClass__time-estimate')
.text(),
'mockTimeEstimate',
);
).toStrictEqual('mockTimeEstimate');
});
it('should render a check if showCheck is true', function () {
it('should render a check if showCheck is true', () => {
const renderButtonContentResult = GasPriceButtonGroup.prototype.renderButtonContent(
{},
{
@ -286,13 +271,12 @@ describe('GasPriceButtonGroup Component', function () {
const wrappedRenderButtonContentResult = shallow(
renderButtonContentResult,
);
assert.strictEqual(
wrappedRenderButtonContentResult.find('.fa-check').length,
expect(wrappedRenderButtonContentResult.find('.fa-check')).toHaveLength(
1,
);
});
it('should render all elements if all args passed', function () {
it('should render all elements if all args passed', () => {
const renderButtonContentResult = wrapper.instance().renderButtonContent(
{
gasEstimateType: 'SLOW',
@ -308,10 +292,10 @@ describe('GasPriceButtonGroup Component', function () {
const wrappedRenderButtonContentResult = shallow(
renderButtonContentResult,
);
assert.strictEqual(wrappedRenderButtonContentResult.children().length, 5);
expect(wrappedRenderButtonContentResult.children()).toHaveLength(5);
});
it('should render no elements if all args passed', function () {
it('should render no elements if all args passed', () => {
const renderButtonContentResult = GasPriceButtonGroup.prototype.renderButtonContent(
{},
{},
@ -319,7 +303,7 @@ describe('GasPriceButtonGroup Component', function () {
const wrappedRenderButtonContentResult = shallow(
renderButtonContentResult,
);
assert.strictEqual(wrappedRenderButtonContentResult.children().length, 0);
expect(wrappedRenderButtonContentResult.children()).toHaveLength(0);
});
});
});

View File

@ -1,11 +1,10 @@
import assert from 'assert';
import React from 'react';
import sinon from 'sinon';
import { shallow } from 'enzyme';
import InfoBox from './info-box.component';
describe('InfoBox', function () {
describe('InfoBox', () => {
let wrapper;
const props = {
@ -14,23 +13,23 @@ describe('InfoBox', function () {
onClose: sinon.spy(),
};
beforeEach(function () {
beforeEach(() => {
wrapper = shallow(<InfoBox {...props} />);
});
it('renders title from props', function () {
it('renders title from props', () => {
const title = wrapper.find('.info-box__title');
assert.strictEqual(title.text(), props.title);
expect(title.text()).toStrictEqual(props.title);
});
it('renders description from props', function () {
it('renders description from props', () => {
const description = wrapper.find('.info-box__description');
assert.strictEqual(description.text(), props.description);
expect(description.text()).toStrictEqual(props.description);
});
it('closes info box', function () {
it('closes info box', () => {
const close = wrapper.find('.info-box__close');
close.simulate('click');
assert(props.onClose.calledOnce);
expect(props.onClose.calledOnce).toStrictEqual(true);
});
});

View File

@ -1,4 +1,3 @@
import assert from 'assert';
import React from 'react';
import { Provider } from 'react-redux';
import configureStore from 'redux-mock-store';
@ -30,22 +29,22 @@ const initState = {
};
const mockStore = configureStore();
describe('MenuBar', function () {
it('opens account detail menu when account options is clicked', function () {
describe('MenuBar', () => {
it('opens account detail menu when account options is clicked', () => {
const store = mockStore(initState);
const wrapper = mountWithRouter(
<Provider store={store}>
<MenuBar />
</Provider>,
);
assert.ok(!wrapper.exists('AccountOptionsMenu'));
expect(!wrapper.exists('AccountOptionsMenu')).toStrictEqual(true);
const accountOptions = wrapper.find('.menu-bar__account-options');
accountOptions.simulate('click');
wrapper.update();
assert.ok(wrapper.exists('AccountOptionsMenu'));
expect(wrapper.exists('AccountOptionsMenu')).toStrictEqual(true);
});
it('sets accountDetailsMenuOpen to false when closed', function () {
it('sets accountDetailsMenuOpen to false when closed', () => {
const store = mockStore(initState);
const wrapper = mountWithRouter(
<Provider store={store}>
@ -55,10 +54,10 @@ describe('MenuBar', function () {
const accountOptions = wrapper.find('.menu-bar__account-options');
accountOptions.simulate('click');
wrapper.update();
assert.ok(wrapper.exists('AccountOptionsMenu'));
expect(wrapper.exists('AccountOptionsMenu')).toStrictEqual(true);
const accountDetailsMenu = wrapper.find('AccountOptionsMenu');
accountDetailsMenu.prop('onClose')();
wrapper.update();
assert.ok(!wrapper.exists('AccountOptionsMenu'));
expect(!wrapper.exists('AccountOptionsMenu')).toStrictEqual(true);
});
});

View File

@ -1,44 +1,39 @@
import assert from 'assert';
import React from 'react';
import { shallow } from 'enzyme';
import ModalContent from './modal-content.component';
describe('ModalContent Component', function () {
it('should render a title', function () {
describe('ModalContent Component', () => {
it('should render a title', () => {
const wrapper = shallow(<ModalContent title="Modal Title" />);
assert.strictEqual(wrapper.find('.modal-content__title').length, 1);
assert.strictEqual(
wrapper.find('.modal-content__title').text(),
expect(wrapper.find('.modal-content__title')).toHaveLength(1);
expect(wrapper.find('.modal-content__title').text()).toStrictEqual(
'Modal Title',
);
assert.strictEqual(wrapper.find('.modal-content__description').length, 0);
expect(wrapper.find('.modal-content__description')).toHaveLength(0);
});
it('should render a description', function () {
it('should render a description', () => {
const wrapper = shallow(<ModalContent description="Modal Description" />);
assert.strictEqual(wrapper.find('.modal-content__title').length, 0);
assert.strictEqual(wrapper.find('.modal-content__description').length, 1);
assert.strictEqual(
wrapper.find('.modal-content__description').text(),
expect(wrapper.find('.modal-content__title')).toHaveLength(0);
expect(wrapper.find('.modal-content__description')).toHaveLength(1);
expect(wrapper.find('.modal-content__description').text()).toStrictEqual(
'Modal Description',
);
});
it('should render both a title and a description', function () {
it('should render both a title and a description', () => {
const wrapper = shallow(
<ModalContent title="Modal Title" description="Modal Description" />,
);
assert.strictEqual(wrapper.find('.modal-content__title').length, 1);
assert.strictEqual(
wrapper.find('.modal-content__title').text(),
expect(wrapper.find('.modal-content__title')).toHaveLength(1);
expect(wrapper.find('.modal-content__title').text()).toStrictEqual(
'Modal Title',
);
assert.strictEqual(wrapper.find('.modal-content__description').length, 1);
assert.strictEqual(
wrapper.find('.modal-content__description').text(),
expect(wrapper.find('.modal-content__description')).toHaveLength(1);
expect(wrapper.find('.modal-content__description').text()).toStrictEqual(
'Modal Description',
);
});

View File

@ -1,21 +1,20 @@
import assert from 'assert';
import React from 'react';
import { mount, shallow } from 'enzyme';
import sinon from 'sinon';
import Button from '../../ui/button';
import Modal from './modal.component';
describe('Modal Component', function () {
it('should render a modal with a submit button', function () {
describe('Modal Component', () => {
it('should render a modal with a submit button', () => {
const wrapper = shallow(<Modal />);
assert.strictEqual(wrapper.find('.modal-container').length, 1);
expect(wrapper.find('.modal-container')).toHaveLength(1);
const buttons = wrapper.find(Button);
assert.strictEqual(buttons.length, 1);
assert.strictEqual(buttons.at(0).props().type, 'secondary');
expect(buttons).toHaveLength(1);
expect(buttons.at(0).props().type).toStrictEqual('secondary');
});
it('should render a modal with a cancel and a submit button', function () {
it('should render a modal with a cancel and a submit button', () => {
const handleCancel = sinon.spy();
const handleSubmit = sinon.spy();
const wrapper = shallow(
@ -28,24 +27,24 @@ describe('Modal Component', function () {
);
const buttons = wrapper.find(Button);
assert.strictEqual(buttons.length, 2);
expect(buttons).toHaveLength(2);
const cancelButton = buttons.at(0);
const submitButton = buttons.at(1);
assert.strictEqual(cancelButton.props().type, 'default');
assert.strictEqual(cancelButton.props().children, 'Cancel');
assert.strictEqual(handleCancel.callCount, 0);
expect(cancelButton.props().type).toStrictEqual('default');
expect(cancelButton.props().children).toStrictEqual('Cancel');
expect(handleCancel.callCount).toStrictEqual(0);
cancelButton.simulate('click');
assert.strictEqual(handleCancel.callCount, 1);
expect(handleCancel.callCount).toStrictEqual(1);
assert.strictEqual(submitButton.props().type, 'secondary');
assert.strictEqual(submitButton.props().children, 'Submit');
assert.strictEqual(handleSubmit.callCount, 0);
expect(submitButton.props().type).toStrictEqual('secondary');
expect(submitButton.props().children).toStrictEqual('Submit');
expect(handleSubmit.callCount).toStrictEqual(0);
submitButton.simulate('click');
assert.strictEqual(handleSubmit.callCount, 1);
expect(handleSubmit.callCount).toStrictEqual(1);
});
it('should render a modal with different button types', function () {
it('should render a modal with different button types', () => {
const wrapper = shallow(
<Modal
onCancel={() => undefined}
@ -58,12 +57,12 @@ describe('Modal Component', function () {
);
const buttons = wrapper.find(Button);
assert.strictEqual(buttons.length, 2);
assert.strictEqual(buttons.at(0).props().type, 'secondary');
assert.strictEqual(buttons.at(1).props().type, 'confirm');
expect(buttons).toHaveLength(2);
expect(buttons.at(0).props().type).toStrictEqual('secondary');
expect(buttons.at(1).props().type).toStrictEqual('confirm');
});
it('should render a modal with children', function () {
it('should render a modal with children', () => {
const wrapper = shallow(
<Modal
onCancel={() => undefined}
@ -74,11 +73,10 @@ describe('Modal Component', function () {
<div className="test-child" />
</Modal>,
);
assert.ok(wrapper.find('.test-class'));
expect(wrapper.find('.test-child')).toHaveLength(1);
});
it('should render a modal with a header', function () {
it('should render a modal with a header', () => {
const handleCancel = sinon.spy();
const handleSubmit = sinon.spy();
const wrapper = shallow(
@ -92,19 +90,18 @@ describe('Modal Component', function () {
/>,
);
assert.ok(wrapper.find('.modal-container__header'));
assert.strictEqual(
wrapper.find('.modal-container__header-text').text(),
expect(wrapper.find('.modal-container__header')).toHaveLength(1);
expect(wrapper.find('.modal-container__header-text').text()).toStrictEqual(
'My Header',
);
assert.strictEqual(handleCancel.callCount, 0);
assert.strictEqual(handleSubmit.callCount, 0);
expect(handleCancel.callCount).toStrictEqual(0);
expect(handleSubmit.callCount).toStrictEqual(0);
wrapper.find('.modal-container__header-close').simulate('click');
assert.strictEqual(handleCancel.callCount, 1);
assert.strictEqual(handleSubmit.callCount, 0);
expect(handleCancel.callCount).toStrictEqual(1);
expect(handleSubmit.callCount).toStrictEqual(0);
});
it('should disable the submit button if submitDisabled is true', function () {
it('should disable the submit button if submitDisabled is true', () => {
const handleCancel = sinon.spy();
const handleSubmit = sinon.spy();
const wrapper = mount(
@ -120,17 +117,17 @@ describe('Modal Component', function () {
);
const buttons = wrapper.find(Button);
assert.strictEqual(buttons.length, 2);
expect(buttons).toHaveLength(2);
const cancelButton = buttons.at(0);
const submitButton = buttons.at(1);
assert.strictEqual(handleCancel.callCount, 0);
expect(handleCancel.callCount).toStrictEqual(0);
cancelButton.simulate('click');
assert.strictEqual(handleCancel.callCount, 1);
expect(handleCancel.callCount).toStrictEqual(1);
assert.strictEqual(submitButton.props().disabled, true);
assert.strictEqual(handleSubmit.callCount, 0);
expect(submitButton.props().disabled).toStrictEqual(true);
expect(handleSubmit.callCount).toStrictEqual(0);
submitButton.simulate('click');
assert.strictEqual(handleSubmit.callCount, 0);
expect(handleSubmit.callCount).toStrictEqual(0);
});
});

View File

@ -1,10 +1,9 @@
import assert from 'assert';
import React from 'react';
import sinon from 'sinon';
import { shallow } from 'enzyme';
import AccountDetailsModal from './account-details-modal.container';
describe('Account Details Modal', function () {
describe('Account Details Modal', () => {
let wrapper;
global.platform = { openTab: sinon.spy() };
@ -33,7 +32,7 @@ describe('Account Details Modal', function () {
},
};
beforeEach(function () {
beforeEach(() => {
wrapper = shallow(<AccountDetailsModal.WrappedComponent {...props} />, {
context: {
t: (str) => str,
@ -41,37 +40,37 @@ describe('Account Details Modal', function () {
});
});
it('sets account label when changing default account label', function () {
it('sets account label when changing default account label', () => {
const accountLabel = wrapper.find('.account-details-modal__name').first();
accountLabel.simulate('submit', 'New Label');
assert(props.setAccountLabel.calledOnce);
assert.strictEqual(props.setAccountLabel.getCall(0).args[1], 'New Label');
expect(props.setAccountLabel.calledOnce).toStrictEqual(true);
expect(props.setAccountLabel.getCall(0).args[1]).toStrictEqual('New Label');
});
it('opens new tab when view block explorer is clicked', function () {
it('opens new tab when view block explorer is clicked', () => {
const modalButton = wrapper.find('.account-details-modal__button');
const etherscanLink = modalButton.first();
etherscanLink.simulate('click');
assert(global.platform.openTab.calledOnce);
expect(global.platform.openTab.calledOnce).toStrictEqual(true);
});
it('shows export private key modal when clicked', function () {
it('shows export private key modal when clicked', () => {
const modalButton = wrapper.find('.account-details-modal__button');
const etherscanLink = modalButton.last();
etherscanLink.simulate('click');
assert(props.showExportPrivateKeyModal.calledOnce);
expect(props.showExportPrivateKeyModal.calledOnce).toStrictEqual(true);
});
it('sets blockexplorerview text when block explorer url in rpcPrefs exists', function () {
it('sets blockexplorerview text when block explorer url in rpcPrefs exists', () => {
const blockExplorerUrl = 'https://block.explorer';
wrapper.setProps({ rpcPrefs: { blockExplorerUrl } });
const modalButton = wrapper.find('.account-details-modal__button');
const blockExplorerLink = modalButton.first().shallow();
assert.strictEqual(blockExplorerLink.text(), 'blockExplorerView');
expect(blockExplorerLink.text()).toStrictEqual('blockExplorerView');
});
});

View File

@ -1,27 +1,24 @@
import assert from 'assert';
import React from 'react';
import { shallow } from 'enzyme';
import UserPreferencedCurrencyDisplay from '../../../user-preferenced-currency-display';
import CancelTransactionGasFee from './cancel-transaction-gas-fee.component';
describe('CancelTransactionGasFee Component', function () {
it('should render', function () {
describe('CancelTransactionGasFee Component', () => {
it('should render', () => {
const wrapper = shallow(<CancelTransactionGasFee value="0x3b9aca00" />);
assert.ok(wrapper);
assert.strictEqual(wrapper.find(UserPreferencedCurrencyDisplay).length, 2);
expect(wrapper.find('.cancel-transaction-gas-fee')).toHaveLength(1);
expect(wrapper.find(UserPreferencedCurrencyDisplay)).toHaveLength(2);
const ethDisplay = wrapper.find(UserPreferencedCurrencyDisplay).at(0);
const fiatDisplay = wrapper.find(UserPreferencedCurrencyDisplay).at(1);
assert.strictEqual(ethDisplay.props().value, '0x3b9aca00');
assert.strictEqual(
ethDisplay.props().className,
expect(ethDisplay.props().value).toStrictEqual('0x3b9aca00');
expect(ethDisplay.props().className).toStrictEqual(
'cancel-transaction-gas-fee__eth',
);
assert.strictEqual(fiatDisplay.props().value, '0x3b9aca00');
assert.strictEqual(
fiatDisplay.props().className,
expect(fiatDisplay.props().value).toStrictEqual('0x3b9aca00');
expect(fiatDisplay.props().className).toStrictEqual(
'cancel-transaction-gas-fee__fiat',
);
});

View File

@ -1,4 +1,3 @@
import assert from 'assert';
import React from 'react';
import { shallow } from 'enzyme';
import sinon from 'sinon';
@ -6,32 +5,28 @@ import Modal from '../../modal';
import CancelTransaction from './cancel-transaction.component';
import CancelTransactionGasFee from './cancel-transaction-gas-fee';
describe('CancelTransaction Component', function () {
describe('CancelTransaction Component', () => {
const t = (key) => key;
it('should render a CancelTransaction modal', function () {
it('should render a CancelTransaction modal', () => {
const wrapper = shallow(<CancelTransaction newGasFee="0x1319718a5000" />, {
context: { t },
});
assert.ok(wrapper);
assert.strictEqual(wrapper.find(Modal).length, 1);
assert.strictEqual(wrapper.find(CancelTransactionGasFee).length, 1);
assert.strictEqual(
wrapper.find(CancelTransactionGasFee).props().value,
expect(wrapper.find(Modal)).toHaveLength(1);
expect(wrapper.find(CancelTransactionGasFee)).toHaveLength(1);
expect(wrapper.find(CancelTransactionGasFee).props().value).toStrictEqual(
'0x1319718a5000',
);
assert.strictEqual(
wrapper.find('.cancel-transaction__title').text(),
expect(wrapper.find('.cancel-transaction__title').text()).toStrictEqual(
'cancellationGasFee',
);
assert.strictEqual(
expect(
wrapper.find('.cancel-transaction__description').text(),
'attemptToCancelDescription',
);
).toStrictEqual('attemptToCancelDescription');
});
it('should pass the correct props to the Modal component', async function () {
it('should pass the correct props to the Modal component', async () => {
const createCancelTransactionSpy = sinon
.stub()
.callsFake(() => Promise.resolve());
@ -47,19 +42,19 @@ describe('CancelTransaction Component', function () {
{ context: { t } },
);
assert.strictEqual(wrapper.find(Modal).length, 1);
expect(wrapper.find(Modal)).toHaveLength(1);
const modalProps = wrapper.find(Modal).props();
assert.strictEqual(modalProps.headerText, 'attemptToCancel');
assert.strictEqual(modalProps.submitText, 'yesLetsTry');
assert.strictEqual(modalProps.cancelText, 'nevermind');
expect(modalProps.headerText).toStrictEqual('attemptToCancel');
expect(modalProps.submitText).toStrictEqual('yesLetsTry');
expect(modalProps.cancelText).toStrictEqual('nevermind');
assert.strictEqual(createCancelTransactionSpy.callCount, 0);
assert.strictEqual(hideModalSpy.callCount, 0);
expect(createCancelTransactionSpy.callCount).toStrictEqual(0);
expect(hideModalSpy.callCount).toStrictEqual(0);
await modalProps.onSubmit();
assert.strictEqual(createCancelTransactionSpy.callCount, 1);
assert.strictEqual(hideModalSpy.callCount, 1);
expect(createCancelTransactionSpy.callCount).toStrictEqual(1);
expect(hideModalSpy.callCount).toStrictEqual(1);
modalProps.onCancel();
assert.strictEqual(hideModalSpy.callCount, 2);
expect(hideModalSpy.callCount).toStrictEqual(2);
});
});

View File

@ -1,10 +1,9 @@
import assert from 'assert';
import React from 'react';
import sinon from 'sinon';
import { mount } from 'enzyme';
import ConfirmDeleteNetwork from './confirm-delete-network.container';
describe('Confirm Delete Network', function () {
describe('Confirm Delete Network', () => {
let wrapper;
const props = {
@ -14,7 +13,7 @@ describe('Confirm Delete Network', function () {
target: '',
};
beforeEach(function () {
beforeEach(() => {
wrapper = mount(<ConfirmDeleteNetwork.WrappedComponent {...props} />, {
context: {
t: (str) => str,
@ -22,37 +21,35 @@ describe('Confirm Delete Network', function () {
});
});
afterEach(function () {
afterEach(() => {
props.hideModal.resetHistory();
props.delRpcTarget.resetHistory();
props.onConfirm.resetHistory();
});
it('renders delete network modal title', function () {
it('renders delete network modal title', () => {
const modalTitle = wrapper.find('.modal-content__title');
assert.strictEqual(modalTitle.text(), 'deleteNetwork');
expect(modalTitle.text()).toStrictEqual('deleteNetwork');
});
it('clicks cancel to hide modal', function () {
it('clicks cancel to hide modal', () => {
const cancelButton = wrapper.find(
'.button.btn-default.modal-container__footer-button',
);
cancelButton.simulate('click');
assert(props.hideModal.calledOnce);
expect(props.hideModal.calledOnce).toStrictEqual(true);
});
it('clicks delete to delete the target and hides modal', function () {
it('clicks delete to delete the target and hides modal', async () => {
const deleteButton = wrapper.find(
'.button.btn-danger.modal-container__footer-button',
);
deleteButton.simulate('click');
setImmediate(() => {
assert(props.delRpcTarget.calledOnce);
assert(props.hideModal.calledOnce);
assert(props.onConfirm.calledOnce);
});
expect(await props.delRpcTarget.calledOnce).toStrictEqual(true);
expect(props.hideModal.calledOnce).toStrictEqual(true);
expect(props.onConfirm.calledOnce).toStrictEqual(true);
});
});

View File

@ -1,4 +1,3 @@
import assert from 'assert';
import React from 'react';
import PropTypes from 'prop-types';
import { Provider } from 'react-redux';
@ -7,7 +6,7 @@ import configureStore from 'redux-mock-store';
import { mount } from 'enzyme';
import ConfirmRemoveAccount from './confirm-remove-account.container';
describe('Confirm Remove Account', function () {
describe('Confirm Remove Account', () => {
let wrapper;
const state = {
@ -27,7 +26,7 @@ describe('Confirm Remove Account', function () {
const mockStore = configureStore();
const store = mockStore(state);
beforeEach(function () {
beforeEach(() => {
wrapper = mount(
<Provider store={store}>
<ConfirmRemoveAccount.WrappedComponent {...props} />
@ -45,37 +44,33 @@ describe('Confirm Remove Account', function () {
);
});
afterEach(function () {
afterEach(() => {
props.hideModal.resetHistory();
});
it('nevermind', function () {
it('nevermind', () => {
const nevermind = wrapper.find({ type: 'default' });
nevermind.simulate('click');
assert(props.hideModal.calledOnce);
expect(props.hideModal.calledOnce).toStrictEqual(true);
});
it('remove', function (done) {
it('remove', async () => {
const remove = wrapper.find({ type: 'secondary' });
remove.simulate('click');
assert(props.removeAccount.calledOnce);
assert.strictEqual(
props.removeAccount.getCall(0).args[0],
expect(await props.removeAccount.calledOnce).toStrictEqual(true);
expect(props.removeAccount.getCall(0).args[0]).toStrictEqual(
props.identity.address,
);
setImmediate(() => {
assert(props.hideModal.calledOnce);
done();
});
expect(props.hideModal.calledOnce).toStrictEqual(true);
});
it('closes', function () {
it('closes', () => {
const close = wrapper.find('.modal-container__header-close');
close.simulate('click');
assert(props.hideModal.calledOnce);
expect(props.hideModal.calledOnce).toStrictEqual(true);
});
});

View File

@ -1,10 +1,9 @@
import assert from 'assert';
import React from 'react';
import sinon from 'sinon';
import { mount } from 'enzyme';
import ConfirmResetAccount from './confirm-reset-account.container';
describe('Confirm Reset Account', function () {
describe('Confirm Reset Account', () => {
let wrapper;
const props = {
@ -12,7 +11,7 @@ describe('Confirm Reset Account', function () {
resetAccount: sinon.stub().resolves(),
};
beforeEach(function () {
beforeEach(() => {
wrapper = mount(<ConfirmResetAccount.WrappedComponent {...props} />, {
context: {
t: (str) => str,
@ -20,27 +19,24 @@ describe('Confirm Reset Account', function () {
});
});
afterEach(function () {
afterEach(() => {
props.hideModal.resetHistory();
});
it('hides modal when nevermind button is clicked', function () {
it('hides modal when nevermind button is clicked', () => {
const nevermind = wrapper.find(
'.btn-default.modal-container__footer-button',
);
nevermind.simulate('click');
assert(props.hideModal.calledOnce);
expect(props.hideModal.calledOnce).toStrictEqual(true);
});
it('resets account and hides modal when reset button is clicked', function (done) {
it('resets account and hides modal when reset button is clicked', async () => {
const reset = wrapper.find('.btn-danger.modal-container__footer-button');
reset.simulate('click');
setImmediate(() => {
assert(props.resetAccount.calledOnce);
assert(props.hideModal.calledOnce);
done();
});
expect(await props.resetAccount.calledOnce).toStrictEqual(true);
expect(props.hideModal.calledOnce).toStrictEqual(true);
});
});

View File

@ -1,11 +1,10 @@
import assert from 'assert';
import React from 'react';
import sinon from 'sinon';
import { mount } from 'enzyme';
import messages from '../../../../../../app/_locales/en/messages.json';
import MetaMetricsOptIn from './metametrics-opt-in-modal.container';
describe('MetaMetrics Opt In', function () {
describe('MetaMetrics Opt In', () => {
let wrapper;
const props = {
@ -14,7 +13,7 @@ describe('MetaMetrics Opt In', function () {
participateInMetaMetrics: null,
};
beforeEach(function () {
beforeEach(() => {
wrapper = mount(<MetaMetricsOptIn.WrappedComponent {...props} />, {
context: {
metricsEvent: () => undefined,
@ -23,40 +22,36 @@ describe('MetaMetrics Opt In', function () {
});
});
afterEach(function () {
afterEach(() => {
props.setParticipateInMetaMetrics.resetHistory();
props.hideModal.resetHistory();
});
it('passes false to setParticipateInMetaMetrics and hides modal', function (done) {
it('passes false to setParticipateInMetaMetrics and hides modal', async () => {
const noThanks = wrapper.find('.btn-default.page-container__footer-button');
noThanks.simulate('click');
setImmediate(() => {
assert(props.setParticipateInMetaMetrics.calledOnce);
assert.strictEqual(
props.setParticipateInMetaMetrics.getCall(0).args[0],
false,
);
assert(props.hideModal.calledOnce);
done();
});
expect(await props.setParticipateInMetaMetrics.calledOnce).toStrictEqual(
true,
);
expect(props.setParticipateInMetaMetrics.getCall(0).args[0]).toStrictEqual(
false,
);
expect(props.hideModal.calledOnce).toStrictEqual(true);
});
it('passes true to setParticipateInMetaMetrics and hides modal', function (done) {
it('passes true to setParticipateInMetaMetrics and hides modal', async () => {
const affirmAgree = wrapper.find(
'.btn-primary.page-container__footer-button',
);
affirmAgree.simulate('click');
setImmediate(() => {
assert(props.setParticipateInMetaMetrics.calledOnce);
assert.strictEqual(
props.setParticipateInMetaMetrics.getCall(0).args[0],
true,
);
assert(props.hideModal.calledOnce);
done();
});
expect(await props.setParticipateInMetaMetrics.calledOnce).toStrictEqual(
true,
);
expect(props.setParticipateInMetaMetrics.getCall(0).args[0]).toStrictEqual(
true,
);
expect(props.hideModal.calledOnce).toStrictEqual(true);
});
});

View File

@ -1,10 +1,9 @@
import assert from 'assert';
import React from 'react';
import sinon from 'sinon';
import { mount } from 'enzyme';
import RejectTransactionsModal from './reject-transactions.container';
describe('Reject Transactions Model', function () {
describe('Reject Transactions Model', () => {
let wrapper;
const props = {
@ -13,7 +12,7 @@ describe('Reject Transactions Model', function () {
unapprovedTxCount: 2,
};
beforeEach(function () {
beforeEach(() => {
wrapper = mount(<RejectTransactionsModal.WrappedComponent {...props} />, {
context: {
t: (str) => str,
@ -21,29 +20,26 @@ describe('Reject Transactions Model', function () {
});
});
afterEach(function () {
afterEach(() => {
props.hideModal.resetHistory();
});
it('hides modal when cancel button is clicked', function () {
it('hides modal when cancel button is clicked', () => {
const cancelButton = wrapper.find(
'.btn-default.modal-container__footer-button',
);
cancelButton.simulate('click');
assert(props.hideModal.calledOnce);
expect(props.hideModal.calledOnce).toStrictEqual(true);
});
it('onSubmit is called and hides modal when reject all clicked', function (done) {
it('onSubmit is called and hides modal when reject all clicked', async () => {
const rejectAllButton = wrapper.find(
'.btn-secondary.modal-container__footer-button',
);
rejectAllButton.simulate('click');
setImmediate(() => {
assert(props.onSubmit.calledOnce);
assert(props.hideModal.calledOnce);
done();
});
expect(await props.onSubmit.calledOnce).toStrictEqual(true);
expect(props.hideModal.calledOnce).toStrictEqual(true);
});
});

View File

@ -1,11 +1,10 @@
import assert from 'assert';
import React from 'react';
import sinon from 'sinon';
import { mount } from 'enzyme';
import TransactionConfirmed from './transaction-confirmed.container';
describe('Transaction Confirmed', function () {
it('clicks ok to submit and hide modal', function () {
describe('Transaction Confirmed', () => {
it('clicks ok to submit and hide modal', () => {
const props = {
onSubmit: sinon.spy(),
hideModal: sinon.spy(),
@ -23,7 +22,7 @@ describe('Transaction Confirmed', function () {
);
submit.simulate('click');
assert(props.onSubmit.calledOnce);
assert(props.hideModal.calledOnce);
expect(props.onSubmit.calledOnce).toStrictEqual(true);
expect(props.hideModal.calledOnce).toStrictEqual(true);
});
});

View File

@ -1,10 +1,9 @@
import assert from 'assert';
import React from 'react';
import { render } from 'enzyme';
import SelectedAccount from './selected-account.component';
describe('SelectedAccount Component', function () {
it('should render checksummed address', function () {
describe('SelectedAccount Component', () => {
it('should render checksummed address', () => {
const wrapper = render(
<SelectedAccount
selectedIdentity={{
@ -15,12 +14,10 @@ describe('SelectedAccount Component', function () {
{ context: { t: () => undefined } },
);
// Checksummed version of address is displayed
assert.strictEqual(
wrapper.find('.selected-account__address').text(),
expect(wrapper.find('.selected-account__address').text()).toStrictEqual(
'0x1B82...5C9D',
);
assert.strictEqual(
wrapper.find('.selected-account__name').text(),
expect(wrapper.find('.selected-account__name').text()).toStrictEqual(
'testName',
);
});

View File

@ -1,4 +1,3 @@
import assert from 'assert';
import React from 'react';
import { shallow } from 'enzyme';
import sinon from 'sinon';
@ -10,10 +9,10 @@ const propsMethodSpies = {
hideSidebar: sinon.spy(),
};
describe('Sidebar Component', function () {
describe('Sidebar Component', () => {
let wrapper;
beforeEach(function () {
beforeEach(() => {
wrapper = shallow(
<Sidebar
sidebarOpen={false}
@ -24,69 +23,77 @@ describe('Sidebar Component', function () {
);
});
afterEach(function () {
afterEach(() => {
propsMethodSpies.hideSidebar.resetHistory();
});
describe('renderOverlay', function () {
describe('renderOverlay', () => {
let renderOverlay;
beforeEach(function () {
beforeEach(() => {
renderOverlay = shallow(wrapper.instance().renderOverlay());
});
it('should render a overlay element', function () {
assert(renderOverlay.hasClass('sidebar-overlay'));
it('should render a overlay element', () => {
expect(renderOverlay.hasClass('sidebar-overlay')).toStrictEqual(true);
});
it('should pass the correct onClick function to the element', function () {
assert.strictEqual(propsMethodSpies.hideSidebar.callCount, 0);
it('should pass the correct onClick function to the element', () => {
expect(propsMethodSpies.hideSidebar.callCount).toStrictEqual(0);
renderOverlay.props().onClick();
assert.strictEqual(propsMethodSpies.hideSidebar.callCount, 1);
expect(propsMethodSpies.hideSidebar.callCount).toStrictEqual(1);
});
});
describe('renderSidebarContent', function () {
describe('renderSidebarContent', () => {
let renderSidebarContent;
beforeEach(function () {
beforeEach(() => {
renderSidebarContent = wrapper.instance().renderSidebarContent();
});
it('should render sidebar content with the type customize-gas', function () {
it('should render sidebar content with the type customize-gas', () => {
renderSidebarContent = wrapper.instance().renderSidebarContent();
const renderedSidebarContent = shallow(renderSidebarContent);
assert(renderedSidebarContent.hasClass('sidebar-left'));
assert(renderedSidebarContent.childAt(0).is(CustomizeGas));
expect(renderedSidebarContent.hasClass('sidebar-left')).toStrictEqual(
true,
);
expect(renderedSidebarContent.childAt(0).is(CustomizeGas)).toStrictEqual(
true,
);
});
it('should not render with an unrecognized type', function () {
it('should not render with an unrecognized type', () => {
wrapper.setProps({ type: 'foobar' });
renderSidebarContent = wrapper.instance().renderSidebarContent();
assert.strictEqual(renderSidebarContent, null);
expect(renderSidebarContent).toBeNull();
});
});
describe('render', function () {
it('should render a div with one child', function () {
assert(wrapper.is('div'));
assert.strictEqual(wrapper.children().length, 1);
describe('render', () => {
it('should render a div with one child', () => {
expect(wrapper.is('div')).toStrictEqual(true);
expect(wrapper.children()).toHaveLength(1);
});
it('should render the ReactCSSTransitionGroup without any children', function () {
assert(wrapper.children().at(0).is(ReactCSSTransitionGroup));
assert.strictEqual(wrapper.children().at(0).children().length, 0);
it('should render the ReactCSSTransitionGroup without any children', () => {
expect(
wrapper.children().at(0).is(ReactCSSTransitionGroup),
).toStrictEqual(true);
expect(wrapper.children().at(0).children()).toHaveLength(0);
});
it('should render sidebar content and the overlay if sidebarOpen is true', function () {
it('should render sidebar content and the overlay if sidebarOpen is true', () => {
wrapper.setProps({ sidebarOpen: true });
assert.strictEqual(wrapper.children().length, 2);
assert(wrapper.children().at(1).hasClass('sidebar-overlay'));
assert.strictEqual(wrapper.children().at(0).children().length, 1);
assert(
expect(wrapper.children()).toHaveLength(2);
expect(
wrapper.children().at(1).hasClass('sidebar-overlay'),
).toStrictEqual(true);
expect(wrapper.children().at(0).children()).toHaveLength(1);
expect(
wrapper.children().at(0).children().at(0).hasClass('sidebar-left'),
);
assert(
).toStrictEqual(true);
expect(
wrapper
.children()
.at(0)
@ -95,7 +102,7 @@ describe('Sidebar Component', function () {
.children()
.at(0)
.is(CustomizeGas),
);
).toBe(true);
});
});
});

View File

@ -1,12 +1,11 @@
import assert from 'assert';
import React from 'react';
import shallow from '../../../../lib/shallow-with-context';
import SignatureRequest from './signature-request.component';
describe('Signature Request Component', function () {
describe('render', function () {
describe('Signature Request Component', () => {
describe('render', () => {
const fromAddress = '0x123456789abcdef';
it('should render a div with one child', function () {
it('should render a div with one child', () => {
const wrapper = shallow(
<SignatureRequest
clearConfirmTransaction={() => undefined}
@ -22,9 +21,9 @@ describe('Signature Request Component', function () {
/>,
);
assert(wrapper.is('div'));
assert.strictEqual(wrapper.length, 1);
assert(wrapper.hasClass('signature-request'));
expect(wrapper.is('div')).toStrictEqual(true);
expect(wrapper).toHaveLength(1);
expect(wrapper.hasClass('signature-request')).toStrictEqual(true);
});
});
});

View File

@ -1,4 +1,3 @@
import assert from 'assert';
import React from 'react';
import { Provider } from 'react-redux';
import sinon from 'sinon';
@ -6,13 +5,13 @@ import configureMockStore from 'redux-mock-store';
import { mountWithRouter } from '../../../../../test/lib/render-helpers';
import SignatureRequest from './signature-request.container';
describe('Signature Request', function () {
describe('Signature Request', () => {
let wrapper;
const mockStore = {
metamask: {
provider: {
type: 'test',
type: 'transparent',
},
accounts: {
'0xd8f6a2ffb0fc5952d16c9768b71cfd35b6399aa5': {
@ -51,7 +50,7 @@ describe('Signature Request', function () {
},
};
beforeEach(function () {
beforeEach(() => {
wrapper = mountWithRouter(
<Provider store={store}>
<SignatureRequest.WrappedComponent {...props} />
@ -60,21 +59,21 @@ describe('Signature Request', function () {
);
});
afterEach(function () {
afterEach(() => {
props.clearConfirmTransaction.resetHistory();
});
it('cancel', function () {
it('cancel', () => {
const cancelButton = wrapper.find('button.btn-default');
cancelButton.simulate('click');
assert(props.cancel.calledOnce);
expect(props.cancel.calledOnce).toStrictEqual(true);
});
it('sign', function () {
it('sign', () => {
const signButton = wrapper.find('button.btn-primary');
signButton.simulate('click');
assert(props.sign.calledOnce);
expect(props.sign.calledOnce).toStrictEqual(true);
});
});

View File

@ -1,4 +1,3 @@
import assert from 'assert';
import React from 'react';
import thunk from 'redux-thunk';
import { Provider } from 'react-redux';
@ -10,7 +9,7 @@ import { MemoryRouter } from 'react-router-dom';
import Identicon from '../../ui/identicon';
import TokenCell from '.';
describe('Token Cell', function () {
describe('Token Cell', () => {
let wrapper;
const state = {
@ -41,7 +40,7 @@ describe('Token Cell', function () {
let onClick;
beforeEach(function () {
beforeEach(() => {
onClick = sinon.stub();
wrapper = mount(
<Provider store={store}>
@ -59,42 +58,38 @@ describe('Token Cell', function () {
);
});
afterEach(function () {
afterEach(() => {
sinon.restore();
});
it('renders Identicon with props from token cell', function () {
assert.strictEqual(
wrapper.find(Identicon).prop('address'),
it('renders Identicon with props from token cell', () => {
expect(wrapper.find(Identicon).prop('address')).toStrictEqual(
'0xAnotherToken',
);
assert.strictEqual(wrapper.find(Identicon).prop('image'), './test-image');
expect(wrapper.find(Identicon).prop('image')).toStrictEqual('./test-image');
});
it('renders token balance', function () {
assert.strictEqual(
wrapper.find('.asset-list-item__token-value').text(),
it('renders token balance', () => {
expect(wrapper.find('.asset-list-item__token-value').text()).toStrictEqual(
'5.000',
);
});
it('renders token symbol', function () {
assert.strictEqual(
wrapper.find('.asset-list-item__token-symbol').text(),
it('renders token symbol', () => {
expect(wrapper.find('.asset-list-item__token-symbol').text()).toStrictEqual(
'TEST',
);
});
it('renders converted fiat amount', function () {
assert.strictEqual(
wrapper.find('.list-item__subheading').text(),
it('renders converted fiat amount', () => {
expect(wrapper.find('.list-item__subheading').text()).toStrictEqual(
'$0.52 USD',
);
});
it('calls onClick when clicked', function () {
assert.ok(!onClick.called);
it('calls onClick when clicked', () => {
expect(!onClick.called).toStrictEqual(true);
wrapper.simulate('click');
assert.ok(onClick.called);
expect(onClick.called).toStrictEqual(true);
});
});

View File

@ -1,10 +1,9 @@
import assert from 'assert';
import React from 'react';
import { shallow } from 'enzyme';
import TransactionActivityLog from './transaction-activity-log.component';
describe('TransactionActivityLog Component', function () {
it('should render properly', function () {
describe('TransactionActivityLog Component', () => {
it('should render properly', () => {
const activities = [
{
eventKey: 'transactionCreated',
@ -54,11 +53,11 @@ describe('TransactionActivityLog Component', function () {
{ context: { t: (str1, str2) => (str2 ? str1 + str2 : str1) } },
);
assert.ok(wrapper.hasClass('transaction-activity-log'));
assert.ok(wrapper.hasClass('test-class'));
expect(wrapper.hasClass('transaction-activity-log')).toStrictEqual(true);
expect(wrapper.hasClass('test-class')).toStrictEqual(true);
});
it('should render inline retry and cancel buttons for earliest pending transaction', function () {
it('should render inline retry and cancel buttons for earliest pending transaction', () => {
const activities = [
{
eventKey: 'transactionCreated',
@ -107,15 +106,14 @@ describe('TransactionActivityLog Component', function () {
{ context: { t: (str1, str2) => (str2 ? str1 + str2 : str1) } },
);
assert.ok(wrapper.hasClass('transaction-activity-log'));
assert.ok(wrapper.hasClass('test-class'));
assert.strictEqual(
wrapper.find('.transaction-activity-log__action-link').length,
expect(wrapper.hasClass('transaction-activity-log')).toStrictEqual(true);
expect(wrapper.hasClass('test-class')).toStrictEqual(true);
expect(wrapper.find('.transaction-activity-log__action-link')).toHaveLength(
2,
);
});
it('should not render inline retry and cancel buttons for newer pending transactions', function () {
it('should not render inline retry and cancel buttons for newer pending transactions', () => {
const activities = [
{
eventKey: 'transactionCreated',
@ -164,10 +162,9 @@ describe('TransactionActivityLog Component', function () {
{ context: { t: (str1, str2) => (str2 ? str1 + str2 : str1) } },
);
assert.ok(wrapper.hasClass('transaction-activity-log'));
assert.ok(wrapper.hasClass('test-class'));
assert.strictEqual(
wrapper.find('.transaction-activity-log__action-link').length,
expect(wrapper.hasClass('transaction-activity-log')).toStrictEqual(true);
expect(wrapper.hasClass('test-class')).toStrictEqual(true);
expect(wrapper.find('.transaction-activity-log__action-link')).toHaveLength(
0,
);
});

View File

@ -1,20 +1,18 @@
import assert from 'assert';
import proxyquire from 'proxyquire';
/* eslint-disable import/unambiguous */
let mapStateToProps;
proxyquire('./transaction-activity-log.container.js', {
'react-redux': {
connect: (ms) => {
mapStateToProps = ms;
return () => ({});
},
jest.mock('react-redux', () => ({
connect: (ms) => {
mapStateToProps = ms;
return () => ({});
},
});
}));
describe('TransactionActivityLog container', function () {
describe('mapStateToProps()', function () {
it('should return the correct props', function () {
require('./transaction-activity-log.container.js');
describe('TransactionActivityLog container', () => {
describe('mapStateToProps()', () => {
it('should return the correct props', () => {
const mockState = {
metamask: {
conversionRate: 280.45,
@ -23,14 +21,14 @@ describe('TransactionActivityLog container', function () {
},
};
assert.deepStrictEqual(mapStateToProps(mockState), {
expect(mapStateToProps(mockState)).toStrictEqual({
conversionRate: 280.45,
nativeCurrency: 'ETH',
rpcPrefs: {},
});
});
it('should return the correct props when on a custom network', function () {
it('should return the correct props when on a custom network', () => {
const mockState = {
metamask: {
conversionRate: 280.45,
@ -49,7 +47,7 @@ describe('TransactionActivityLog container', function () {
},
};
assert.deepStrictEqual(mapStateToProps(mockState), {
expect(mapStateToProps(mockState)).toStrictEqual({
conversionRate: 280.45,
nativeCurrency: 'ETH',
rpcPrefs: {

View File

@ -1,4 +1,3 @@
import assert from 'assert';
import {
ROPSTEN_CHAIN_ID,
ROPSTEN_NETWORK_ID,
@ -12,13 +11,13 @@ import {
getActivities,
} from './transaction-activity-log.util';
describe('TransactionActivityLog utils', function () {
describe('combineTransactionHistories', function () {
it('should return no activities for an empty list of transactions', function () {
assert.deepStrictEqual(combineTransactionHistories([]), []);
describe('TransactionActivityLog utils', () => {
describe('combineTransactionHistories', () => {
it('should return no activities for an empty list of transactions', () => {
expect(combineTransactionHistories([])).toStrictEqual([]);
});
it('should return activities for an array of transactions', function () {
it('should return activities for an array of transactions', () => {
const transactions = [
{
hash:
@ -233,15 +232,12 @@ describe('TransactionActivityLog utils', function () {
},
];
assert.deepStrictEqual(
combineTransactionHistories(transactions),
expected,
);
expect(combineTransactionHistories(transactions)).toStrictEqual(expected);
});
});
describe('getActivities', function () {
it('should return no activities for an empty history', function () {
describe('getActivities', () => {
it('should return no activities for an empty history', () => {
const transaction = {
history: [],
id: 1,
@ -256,10 +252,10 @@ describe('TransactionActivityLog utils', function () {
},
};
assert.deepStrictEqual(getActivities(transaction), []);
expect(getActivities(transaction)).toStrictEqual([]);
});
it("should return activities for a transaction's history", function () {
it("should return activities for a transaction's history", () => {
const transaction = {
history: [
{
@ -440,7 +436,7 @@ describe('TransactionActivityLog utils', function () {
},
];
assert.deepStrictEqual(getActivities(transaction, true), expectedResult);
expect(getActivities(transaction, true)).toStrictEqual(expectedResult);
});
});
});

View File

@ -1,11 +1,10 @@
import assert from 'assert';
import React from 'react';
import { shallow } from 'enzyme';
import Button from '../../../ui/button';
import TransactionBreakdownRow from './transaction-breakdown-row.component';
describe('TransactionBreakdownRow Component', function () {
it('should render text properly', function () {
describe('TransactionBreakdownRow Component', () => {
it('should render text properly', () => {
const wrapper = shallow(
<TransactionBreakdownRow title="test" className="test-class">
Test
@ -13,18 +12,16 @@ describe('TransactionBreakdownRow Component', function () {
{ context: { t: (str1, str2) => (str2 ? str1 + str2 : str1) } },
);
assert.ok(wrapper.hasClass('transaction-breakdown-row'));
assert.strictEqual(
expect(wrapper.hasClass('transaction-breakdown-row')).toStrictEqual(true);
expect(
wrapper.find('.transaction-breakdown-row__title').text(),
'test',
);
assert.strictEqual(
).toStrictEqual('test');
expect(
wrapper.find('.transaction-breakdown-row__value').text(),
'Test',
);
).toStrictEqual('Test');
});
it('should render components properly', function () {
it('should render components properly', () => {
const wrapper = shallow(
<TransactionBreakdownRow title="test" className="test-class">
<Button onClick={() => undefined}>Button</Button>
@ -32,11 +29,12 @@ describe('TransactionBreakdownRow Component', function () {
{ context: { t: (str1, str2) => (str2 ? str1 + str2 : str1) } },
);
assert.ok(wrapper.hasClass('transaction-breakdown-row'));
assert.strictEqual(
expect(wrapper.hasClass('transaction-breakdown-row')).toStrictEqual(true);
expect(
wrapper.find('.transaction-breakdown-row__title').text(),
'test',
);
assert.ok(wrapper.find('.transaction-breakdown-row__value').find(Button));
).toStrictEqual('test');
expect(
wrapper.find('.transaction-breakdown-row__value').find(Button),
).toHaveLength(1);
});
});

View File

@ -1,11 +1,10 @@
import assert from 'assert';
import React from 'react';
import { shallow } from 'enzyme';
import { TRANSACTION_STATUSES } from '../../../../../shared/constants/transaction';
import TransactionBreakdown from './transaction-breakdown.component';
describe('TransactionBreakdown Component', function () {
it('should render properly', function () {
describe('TransactionBreakdown Component', () => {
it('should render properly', () => {
const transaction = {
history: [],
id: 1,
@ -25,7 +24,7 @@ describe('TransactionBreakdown Component', function () {
{ context: { t: (str1, str2) => (str2 ? str1 + str2 : str1) } },
);
assert.ok(wrapper.hasClass('transaction-breakdown'));
assert.ok(wrapper.hasClass('test-class'));
expect(wrapper.hasClass('transaction-breakdown')).toStrictEqual(true);
expect(wrapper.hasClass('test-class')).toStrictEqual(true);
});
});

View File

@ -1,4 +1,3 @@
import assert from 'assert';
import React from 'react';
import { shallow } from 'enzyme';
import Button from '../../ui/button';
@ -8,8 +7,8 @@ import TransactionActivityLog from '../transaction-activity-log';
import { TRANSACTION_STATUSES } from '../../../../../shared/constants/transaction';
import TransactionListItemDetails from './transaction-list-item-details.component';
describe('TransactionListItemDetails Component', function () {
it('should render properly', function () {
describe('TransactionListItemDetails Component', () => {
it('should render properly', () => {
const transaction = {
history: [],
id: 1,
@ -32,6 +31,7 @@ describe('TransactionListItemDetails Component', function () {
const wrapper = shallow(
<TransactionListItemDetails
onClose={() => undefined}
title="Test Transaction Details"
recipientAddress="0x1"
senderAddress="0x2"
@ -43,14 +43,14 @@ describe('TransactionListItemDetails Component', function () {
{ context: { t: (str1, str2) => (str2 ? str1 + str2 : str1) } },
);
const child = wrapper.childAt(0);
assert.ok(child.hasClass('transaction-list-item-details'));
assert.strictEqual(child.find(Button).length, 2);
assert.strictEqual(child.find(SenderToRecipient).length, 1);
assert.strictEqual(child.find(TransactionBreakdown).length, 1);
assert.strictEqual(child.find(TransactionActivityLog).length, 1);
expect(child.hasClass('transaction-list-item-details')).toStrictEqual(true);
expect(child.find(Button)).toHaveLength(2);
expect(child.find(SenderToRecipient)).toHaveLength(1);
expect(child.find(TransactionBreakdown)).toHaveLength(1);
expect(child.find(TransactionActivityLog)).toHaveLength(1);
});
it('should render a retry button', function () {
it('should render a retry button', () => {
const transaction = {
history: [],
id: 1,
@ -76,6 +76,8 @@ describe('TransactionListItemDetails Component', function () {
const wrapper = shallow(
<TransactionListItemDetails
onClose={() => undefined}
title="Test Transaction Details"
recipientAddress="0x1"
senderAddress="0x2"
tryReverseResolveAddress={() => undefined}
@ -89,15 +91,15 @@ describe('TransactionListItemDetails Component', function () {
const child = wrapper.childAt(0);
assert.ok(child.hasClass('transaction-list-item-details'));
assert.strictEqual(child.find(Button).length, 3);
expect(child.hasClass('transaction-list-item-details')).toStrictEqual(true);
expect(child.find(Button)).toHaveLength(3);
});
it('should disable the Copy Tx ID and View In Etherscan buttons when tx hash is missing', function () {
it('should disable the Copy Tx ID and View In Etherscan buttons when tx hash is missing', () => {
const transaction = {
history: [],
id: 1,
status: TRANSACTION_STATUSES.CONFIRMED,
status: 'confirmed',
txParams: {
from: '0x1',
gas: '0x5208',
@ -116,6 +118,8 @@ describe('TransactionListItemDetails Component', function () {
const wrapper = shallow(
<TransactionListItemDetails
onClose={() => undefined}
title="Test Transaction Details"
recipientAddress="0x1"
senderAddress="0x2"
tryReverseResolveAddress={() => undefined}
@ -128,17 +132,17 @@ describe('TransactionListItemDetails Component', function () {
const child = wrapper.childAt(0);
assert.ok(child.hasClass('transaction-list-item-details'));
expect(child.hasClass('transaction-list-item-details')).toStrictEqual(true);
const buttons = child.find(Button);
assert.strictEqual(buttons.at(0).prop('disabled'), true);
assert.strictEqual(buttons.at(1).prop('disabled'), true);
expect(buttons.at(0).prop('disabled')).toStrictEqual(true);
expect(buttons.at(1).prop('disabled')).toStrictEqual(true);
});
it('should render functional Copy Tx ID and View In Etherscan buttons when tx hash exists', function () {
it('should render functional Copy Tx ID and View In Etherscan buttons when tx hash exists', () => {
const transaction = {
history: [],
id: 1,
status: TRANSACTION_STATUSES.CONFIRMED,
status: 'confirmed',
hash: '0xaa',
txParams: {
from: '0x1',
@ -158,6 +162,8 @@ describe('TransactionListItemDetails Component', function () {
const wrapper = shallow(
<TransactionListItemDetails
onClose={() => undefined}
title="Test Transaction Details"
recipientAddress="0x1"
senderAddress="0x2"
tryReverseResolveAddress={() => undefined}
@ -170,9 +176,9 @@ describe('TransactionListItemDetails Component', function () {
const child = wrapper.childAt(0);
assert.ok(child.hasClass('transaction-list-item-details'));
expect(child.hasClass('transaction-list-item-details')).toStrictEqual(true);
const buttons = child.find(Button);
assert.strictEqual(buttons.at(0).prop('disabled'), false);
assert.strictEqual(buttons.at(1).prop('disabled'), false);
expect(buttons.at(0).prop('disabled')).toStrictEqual(false);
expect(buttons.at(1).prop('disabled')).toStrictEqual(false);
});
});

View File

@ -1,4 +1,3 @@
import assert from 'assert';
import React from 'react';
import { mount } from 'enzyme';
import sinon from 'sinon';
@ -6,21 +5,25 @@ import * as i18nHook from '../../../hooks/useI18nContext';
import Tooltip from '../../ui/tooltip';
import TransactionStatus from './transaction-status.component';
describe('TransactionStatus Component', function () {
before(function () {
describe('TransactionStatus Component', () => {
beforeAll(() => {
sinon.stub(i18nHook, 'useI18nContext').returns((str) => str.toUpperCase());
});
it('should render CONFIRMED properly', function () {
afterAll(() => {
sinon.restore();
});
it('should render CONFIRMED properly', () => {
const wrapper = mount(
<TransactionStatus status="confirmed" date="June 1" />,
);
assert.ok(wrapper);
assert.strictEqual(wrapper.text(), 'June 1');
expect(wrapper.find(TransactionStatus)).toHaveLength(1);
expect(wrapper.text()).toStrictEqual('June 1');
});
it('should render PENDING properly when status is APPROVED', function () {
it('should render PENDING properly when status is APPROVED', () => {
const wrapper = mount(
<TransactionStatus
status="approved"
@ -29,43 +32,32 @@ describe('TransactionStatus Component', function () {
/>,
);
assert.ok(wrapper);
assert.strictEqual(wrapper.text(), 'PENDING');
assert.strictEqual(wrapper.find(Tooltip).props().title, 'test-title');
expect(wrapper.text()).toStrictEqual('PENDING');
expect(wrapper.find(Tooltip).props().title).toStrictEqual('test-title');
});
it('should render PENDING properly', function () {
it('should render PENDING properly', () => {
const wrapper = mount(
<TransactionStatus date="June 1" status="submitted" isEarliestNonce />,
);
assert.ok(wrapper);
assert.strictEqual(wrapper.text(), 'PENDING');
expect(wrapper.find(TransactionStatus)).toHaveLength(1);
expect(wrapper.text()).toStrictEqual('PENDING');
});
it('should render QUEUED properly', function () {
it('should render QUEUED properly', () => {
const wrapper = mount(<TransactionStatus status="queued" />);
assert.ok(wrapper);
assert.ok(
wrapper.find('.transaction-status--queued').length,
'queued className not found',
);
assert.strictEqual(wrapper.text(), 'QUEUED');
expect(wrapper.find(TransactionStatus)).toHaveLength(1);
expect(wrapper.find('.transaction-status--queued')).toHaveLength(1);
expect(wrapper.text()).toStrictEqual('QUEUED');
});
it('should render UNAPPROVED properly', function () {
it('should render UNAPPROVED properly', () => {
const wrapper = mount(<TransactionStatus status="unapproved" />);
assert.ok(wrapper);
assert.ok(
wrapper.find('.transaction-status--unapproved').length,
'unapproved className not found',
);
assert.strictEqual(wrapper.text(), 'UNAPPROVED');
});
after(function () {
sinon.restore();
expect(wrapper.find(TransactionStatus)).toHaveLength(1);
expect(wrapper.find('.transaction-status--unapproved')).toHaveLength(1);
expect(wrapper.text()).toStrictEqual('UNAPPROVED');
});
});

View File

@ -1,4 +1,3 @@
import assert from 'assert';
import React from 'react';
import { shallow } from 'enzyme';
import sinon from 'sinon';
@ -7,34 +6,36 @@ import * as currencyHook from '../../../hooks/useCurrencyDisplay';
import * as currencyPrefHook from '../../../hooks/useUserPreferencedCurrency';
import UserPreferencedCurrencyDisplay from './user-preferenced-currency-display.component';
describe('UserPreferencedCurrencyDisplay Component', function () {
describe('rendering', function () {
beforeEach(function () {
describe('UserPreferencedCurrencyDisplay Component', () => {
describe('rendering', () => {
beforeEach(() => {
sinon.stub(currencyHook, 'useCurrencyDisplay').returns(['1', {}]);
sinon
.stub(currencyPrefHook, 'useUserPreferencedCurrency')
.returns({ currency: 'ETH', decimals: 6 });
});
it('should render properly', function () {
const wrapper = shallow(<UserPreferencedCurrencyDisplay />);
assert.ok(wrapper);
assert.strictEqual(wrapper.find(CurrencyDisplay).length, 1);
afterEach(() => {
sinon.restore();
});
it('should pass all props to the CurrencyDisplay child component', function () {
it('should render properly', () => {
const wrapper = shallow(<UserPreferencedCurrencyDisplay />);
expect(wrapper).toHaveLength(1);
expect(wrapper.find(CurrencyDisplay)).toHaveLength(1);
});
it('should pass all props to the CurrencyDisplay child component', () => {
const wrapper = shallow(
<UserPreferencedCurrencyDisplay prop1 prop2="test" prop3={1} />,
);
assert.ok(wrapper);
assert.strictEqual(wrapper.find(CurrencyDisplay).length, 1);
assert.strictEqual(wrapper.find(CurrencyDisplay).props().prop1, true);
assert.strictEqual(wrapper.find(CurrencyDisplay).props().prop2, 'test');
assert.strictEqual(wrapper.find(CurrencyDisplay).props().prop3, 1);
});
afterEach(function () {
sinon.restore();
expect(wrapper).toHaveLength(1);
expect(wrapper.find(CurrencyDisplay)).toHaveLength(1);
expect(wrapper.find(CurrencyDisplay).props().prop1).toStrictEqual(true);
expect(wrapper.find(CurrencyDisplay).props().prop2).toStrictEqual('test');
expect(wrapper.find(CurrencyDisplay).props().prop3).toStrictEqual(1);
});
});
});

View File

@ -1,28 +1,27 @@
import assert from 'assert';
import React from 'react';
import { shallow } from 'enzyme';
import CurrencyInput from '../../ui/currency-input';
import UserPreferencedCurrencyInput from './user-preferenced-currency-input.component';
describe('UserPreferencedCurrencyInput Component', function () {
describe('rendering', function () {
it('should render properly', function () {
describe('UserPreferencedCurrencyInput Component', () => {
describe('rendering', () => {
it('should render properly', () => {
const wrapper = shallow(<UserPreferencedCurrencyInput />);
assert.ok(wrapper);
assert.strictEqual(wrapper.find(CurrencyInput).length, 1);
expect(wrapper).toHaveLength(1);
expect(wrapper.find(CurrencyInput)).toHaveLength(1);
});
it('should render useFiat for CurrencyInput based on preferences.useNativeCurrencyAsPrimaryCurrency', function () {
it('should render useFiat for CurrencyInput based on preferences.useNativeCurrencyAsPrimaryCurrency', () => {
const wrapper = shallow(
<UserPreferencedCurrencyInput useNativeCurrencyAsPrimaryCurrency />,
);
assert.ok(wrapper);
assert.strictEqual(wrapper.find(CurrencyInput).length, 1);
assert.strictEqual(wrapper.find(CurrencyInput).props().useFiat, false);
expect(wrapper).toHaveLength(1);
expect(wrapper.find(CurrencyInput)).toHaveLength(1);
expect(wrapper.find(CurrencyInput).props().useFiat).toStrictEqual(false);
wrapper.setProps({ useNativeCurrencyAsPrimaryCurrency: false });
assert.strictEqual(wrapper.find(CurrencyInput).props().useFiat, true);
expect(wrapper.find(CurrencyInput).props().useFiat).toStrictEqual(true);
});
});
});

View File

@ -1,20 +1,18 @@
import assert from 'assert';
import proxyquire from 'proxyquire';
/* eslint-disable import/unambiguous */
let mapStateToProps;
proxyquire('./user-preferenced-currency-input.container.js', {
'react-redux': {
connect: (ms) => {
mapStateToProps = ms;
return () => ({});
},
jest.mock('react-redux', () => ({
connect: (ms) => {
mapStateToProps = ms;
return () => ({});
},
});
}));
describe('UserPreferencedCurrencyInput container', function () {
describe('mapStateToProps()', function () {
it('should return the correct props', function () {
require('./user-preferenced-currency-input.container.js');
describe('UserPreferencedCurrencyInput container', () => {
describe('mapStateToProps()', () => {
it('should return the correct props', () => {
const mockState = {
metamask: {
preferences: {
@ -23,7 +21,7 @@ describe('UserPreferencedCurrencyInput container', function () {
},
};
assert.deepStrictEqual(mapStateToProps(mockState), {
expect(mapStateToProps(mockState)).toStrictEqual({
useNativeCurrencyAsPrimaryCurrency: true,
});
});

View File

@ -1,21 +1,20 @@
import assert from 'assert';
import React from 'react';
import { shallow } from 'enzyme';
import TokenInput from '../../ui/token-input';
import UserPreferencedTokenInput from './user-preferenced-token-input.component';
describe('UserPreferencedCurrencyInput Component', function () {
describe('rendering', function () {
it('should render properly', function () {
describe('UserPreferencedCurrencyInput Component', () => {
describe('rendering', () => {
it('should render properly', () => {
const wrapper = shallow(
<UserPreferencedTokenInput token={{ address: '0x0' }} />,
);
assert.ok(wrapper);
assert.strictEqual(wrapper.find(TokenInput).length, 1);
expect(wrapper).toHaveLength(1);
expect(wrapper.find(TokenInput)).toHaveLength(1);
});
it('should render showFiat for TokenInput based on preferences.useNativeCurrencyAsPrimaryCurrency', function () {
it('should render showFiat for TokenInput based on preferences.useNativeCurrencyAsPrimaryCurrency', () => {
const wrapper = shallow(
<UserPreferencedTokenInput
token={{ address: '0x0' }}
@ -23,11 +22,11 @@ describe('UserPreferencedCurrencyInput Component', function () {
/>,
);
assert.ok(wrapper);
assert.strictEqual(wrapper.find(TokenInput).length, 1);
assert.strictEqual(wrapper.find(TokenInput).props().showFiat, false);
expect(wrapper).toHaveLength(1);
expect(wrapper.find(TokenInput)).toHaveLength(1);
expect(wrapper.find(TokenInput).props().showFiat).toStrictEqual(false);
wrapper.setProps({ useNativeCurrencyAsPrimaryCurrency: false });
assert.strictEqual(wrapper.find(TokenInput).props().showFiat, true);
expect(wrapper.find(TokenInput).props().showFiat).toStrictEqual(true);
});
});
});

View File

@ -1,20 +1,18 @@
import assert from 'assert';
import proxyquire from 'proxyquire';
// eslint-disable-next-line import/unambiguous
let mapStateToProps;
proxyquire('./user-preferenced-token-input.container.js', {
'react-redux': {
connect: (ms) => {
mapStateToProps = ms;
return () => ({});
},
jest.mock('react-redux', () => ({
connect: (ms) => {
mapStateToProps = ms;
return () => ({});
},
});
}));
describe('UserPreferencedTokenInput container', function () {
describe('mapStateToProps()', function () {
it('should return the correct props', function () {
require('./user-preferenced-token-input.container.js');
describe('UserPreferencedTokenInput container', () => {
describe('mapStateToProps()', () => {
it('should return the correct props', () => {
const mockState = {
metamask: {
preferences: {
@ -23,7 +21,7 @@ describe('UserPreferencedTokenInput container', function () {
},
};
assert.deepStrictEqual(mapStateToProps(mockState), {
expect(mapStateToProps(mockState)).toStrictEqual({
useNativeCurrencyAsPrimaryCurrency: true,
});
});

View File

@ -1,4 +1,3 @@
import assert from 'assert';
import React from 'react';
import * as reactRedux from 'react-redux';
import sinon from 'sinon';
@ -7,8 +6,8 @@ import InfoIcon from '../icon/info-icon.component';
import { getSelectedAccount } from '../../../selectors';
import AccountMismatchWarning from './account-mismatch-warning.component';
describe('AccountMismatchWarning', function () {
before(function () {
describe('AccountMismatchWarning', () => {
beforeAll(() => {
sinon.stub(reactRedux, 'useSelector').callsFake((selector) => {
if (selector === getSelectedAccount) {
return { address: 'mockedAddress' };
@ -18,17 +17,19 @@ describe('AccountMismatchWarning', function () {
);
});
});
it('renders nothing when the addresses match', function () {
const wrapper = shallow(<AccountMismatchWarning address="mockedAddress" />);
assert.strictEqual(wrapper.find(InfoIcon).length, 0);
afterAll(() => {
sinon.restore();
});
it('renders a warning info icon when addresses do not match', function () {
it('renders nothing when the addresses match', () => {
const wrapper = shallow(<AccountMismatchWarning address="mockedAddress" />);
expect(wrapper.find(InfoIcon)).toHaveLength(0);
});
it('renders a warning info icon when addresses do not match', () => {
const wrapper = shallow(
<AccountMismatchWarning address="mockedAddress2" />,
);
assert.strictEqual(wrapper.find(InfoIcon).length, 1);
});
after(function () {
sinon.restore();
expect(wrapper.find(InfoIcon)).toHaveLength(1);
});
});

View File

@ -1,41 +1,40 @@
import assert from 'assert';
import React from 'react';
import sinon from 'sinon';
import { shallow } from 'enzyme';
import Alert from '.';
describe('Alert', function () {
describe('Alert', () => {
let wrapper;
beforeEach(function () {
wrapper = shallow(<Alert />);
beforeEach(() => {
wrapper = shallow(<Alert visible={false} />);
});
it('renders nothing with no visible boolean in state', function () {
it('renders nothing with no visible boolean in state', () => {
const alert = wrapper.find('.global-alert');
assert.strictEqual(alert.length, 0);
expect(alert).toHaveLength(0);
});
it('renders when visible in state is true, and message', function () {
it('renders when visible in state is true, and message', () => {
const errorMessage = 'Error Message';
wrapper.setState({ visible: true, msg: errorMessage });
const alert = wrapper.find('.global-alert');
assert.strictEqual(alert.length, 1);
expect(alert).toHaveLength(1);
const errorText = wrapper.find('.msg');
assert.strictEqual(errorText.text(), errorMessage);
expect(errorText.text()).toStrictEqual(errorMessage);
});
it('calls component method when componentWillReceiveProps is called', function () {
it('calls component method when componentWillReceiveProps is called', () => {
const animateInSpy = sinon.stub(wrapper.instance(), 'animateIn');
const animateOutSpy = sinon.stub(wrapper.instance(), 'animateOut');
wrapper.setProps({ visible: true });
assert(animateInSpy.calledOnce);
expect(animateInSpy.calledOnce).toStrictEqual(true);
wrapper.setProps({ visible: false });
assert(animateOutSpy.calledOnce);
expect(animateOutSpy.calledOnce).toStrictEqual(true);
});
});

View File

@ -1,26 +1,22 @@
import assert from 'assert';
import React from 'react';
import { shallow } from 'enzyme';
import Breadcrumbs from './breadcrumbs.component';
describe('Breadcrumbs Component', function () {
it('should render with the correct colors', function () {
describe('Breadcrumbs Component', () => {
it('should render with the correct colors', () => {
const wrapper = shallow(<Breadcrumbs currentIndex={1} total={3} />);
assert.ok(wrapper);
assert.strictEqual(wrapper.find('.breadcrumbs').length, 1);
assert.strictEqual(wrapper.find('.breadcrumb').length, 3);
assert.strictEqual(
expect(wrapper).toHaveLength(1);
expect(wrapper.find('.breadcrumbs')).toHaveLength(1);
expect(wrapper.find('.breadcrumb')).toHaveLength(3);
expect(
wrapper.find('.breadcrumb').at(0).props().style.backgroundColor,
'#FFFFFF',
);
assert.strictEqual(
).toStrictEqual('#FFFFFF');
expect(
wrapper.find('.breadcrumb').at(1).props().style.backgroundColor,
'#D8D8D8',
);
assert.strictEqual(
).toStrictEqual('#D8D8D8');
expect(
wrapper.find('.breadcrumb').at(2).props().style.backgroundColor,
'#FFFFFF',
);
).toStrictEqual('#FFFFFF');
});
});

View File

@ -1,10 +1,9 @@
import assert from 'assert';
import React from 'react';
import { shallow } from 'enzyme';
import sinon from 'sinon';
import ButtonGroup from './button-group.component';
describe('ButtonGroup Component', function () {
describe('ButtonGroup Component', () => {
let wrapper;
const childButtonSpies = {
@ -19,12 +18,12 @@ describe('ButtonGroup Component', function () {
<button onClick={childButtonSpies.onClick} key="c"></button>,
];
before(function () {
beforeAll(() => {
sinon.spy(ButtonGroup.prototype, 'handleButtonClick');
sinon.spy(ButtonGroup.prototype, 'renderButtons');
});
beforeEach(function () {
beforeEach(() => {
wrapper = shallow(
<ButtonGroup
defaultActiveButtonIndex={1}
@ -37,92 +36,95 @@ describe('ButtonGroup Component', function () {
);
});
afterEach(function () {
afterEach(() => {
childButtonSpies.onClick.resetHistory();
ButtonGroup.prototype.handleButtonClick.resetHistory();
ButtonGroup.prototype.renderButtons.resetHistory();
});
after(function () {
afterAll(() => {
sinon.restore();
});
describe('componentDidUpdate', function () {
it('should set the activeButtonIndex to the updated newActiveButtonIndex', function () {
assert.strictEqual(wrapper.state('activeButtonIndex'), 1);
describe('componentDidUpdate', () => {
it('should set the activeButtonIndex to the updated newActiveButtonIndex', () => {
expect(wrapper.state('activeButtonIndex')).toStrictEqual(1);
wrapper.setProps({ newActiveButtonIndex: 2 });
assert.strictEqual(wrapper.state('activeButtonIndex'), 2);
expect(wrapper.state('activeButtonIndex')).toStrictEqual(2);
});
it('should not set the activeButtonIndex to an updated newActiveButtonIndex that is not a number', function () {
assert.strictEqual(wrapper.state('activeButtonIndex'), 1);
it('should not set the activeButtonIndex to an updated newActiveButtonIndex that is not a number', () => {
expect(wrapper.state('activeButtonIndex')).toStrictEqual(1);
wrapper.setProps({ newActiveButtonIndex: null });
assert.strictEqual(wrapper.state('activeButtonIndex'), 1);
expect(wrapper.state('activeButtonIndex')).toStrictEqual(1);
});
});
describe('handleButtonClick', function () {
it('should set the activeButtonIndex', function () {
assert.strictEqual(wrapper.state('activeButtonIndex'), 1);
describe('handleButtonClick', () => {
it('should set the activeButtonIndex', () => {
expect(wrapper.state('activeButtonIndex')).toStrictEqual(1);
wrapper.instance().handleButtonClick(2);
assert.strictEqual(wrapper.state('activeButtonIndex'), 2);
expect(wrapper.state('activeButtonIndex')).toStrictEqual(2);
});
});
describe('renderButtons', function () {
it('should render a button for each child', function () {
describe('renderButtons', () => {
it('should render a button for each child', () => {
const childButtons = wrapper.find('.button-group__button');
assert.strictEqual(childButtons.length, 3);
expect(childButtons).toHaveLength(3);
});
it('should render the correct button with an active state', function () {
it('should render the correct button with an active state', () => {
const childButtons = wrapper.find('.button-group__button');
const activeChildButton = wrapper.find('.button-group__button--active');
assert.deepStrictEqual(childButtons.get(1), activeChildButton.get(0));
expect(childButtons.get(1)).toStrictEqual(activeChildButton.get(0));
});
it("should call handleButtonClick and the respective button's onClick method when a button is clicked", function () {
assert.strictEqual(ButtonGroup.prototype.handleButtonClick.callCount, 0);
assert.strictEqual(childButtonSpies.onClick.callCount, 0);
it("should call handleButtonClick and the respective button's onClick method when a button is clicked", () => {
expect(ButtonGroup.prototype.handleButtonClick.callCount).toStrictEqual(
0,
);
expect(childButtonSpies.onClick.callCount).toStrictEqual(0);
const childButtons = wrapper.find('.button-group__button');
childButtons.at(0).props().onClick();
childButtons.at(1).props().onClick();
childButtons.at(2).props().onClick();
assert.strictEqual(ButtonGroup.prototype.handleButtonClick.callCount, 3);
assert.strictEqual(childButtonSpies.onClick.callCount, 3);
expect(ButtonGroup.prototype.handleButtonClick.callCount).toStrictEqual(
3,
);
expect(childButtonSpies.onClick.callCount).toStrictEqual(3);
});
it('should render all child buttons as disabled if props.disabled is true', function () {
it('should render all child buttons as disabled if props.disabled is true', () => {
const childButtons = wrapper.find('.button-group__button');
childButtons.forEach((button) => {
assert.strictEqual(button.props().disabled, undefined);
expect(button.props().disabled).toBeUndefined();
});
wrapper.setProps({ disabled: true });
const disabledChildButtons = wrapper.find('[disabled=true]');
assert.strictEqual(disabledChildButtons.length, 3);
expect(disabledChildButtons).toHaveLength(3);
});
it('should render the children of the button', function () {
it('should render the children of the button', () => {
const mockClass = wrapper.find('.mockClass');
assert.strictEqual(mockClass.length, 1);
expect(mockClass).toHaveLength(1);
});
});
describe('render', function () {
it('should render a div with the expected class and style', function () {
assert.strictEqual(
wrapper.find('div').at(0).props().className,
describe('render', () => {
it('should render a div with the expected class and style', () => {
expect(wrapper.find('div').at(0).props().className).toStrictEqual(
'someClassName',
);
assert.deepStrictEqual(wrapper.find('div').at(0).props().style, {
expect(wrapper.find('div').at(0).props().style).toStrictEqual({
color: 'red',
});
});
it('should call renderButtons when rendering', function () {
assert.strictEqual(ButtonGroup.prototype.renderButtons.callCount, 1);
it('should call renderButtons when rendering', () => {
expect(ButtonGroup.prototype.renderButtons.callCount).toStrictEqual(1);
wrapper.instance().render();
assert.strictEqual(ButtonGroup.prototype.renderButtons.callCount, 2);
expect(ButtonGroup.prototype.renderButtons.callCount).toStrictEqual(2);
});
});
});

View File

@ -1,22 +1,21 @@
import assert from 'assert';
import React from 'react';
import { shallow } from 'enzyme';
import Card from './card.component';
describe('Card Component', function () {
it('should render a card with a title and child element', function () {
describe('Card Component', () => {
it('should render a card with a title and child element', () => {
const wrapper = shallow(
<Card title="Test" className="card-test-class">
<div className="child-test-class">Child</div>
</Card>,
);
assert.ok(wrapper.hasClass('card-test-class'));
expect(wrapper.hasClass('card-test-class')).toStrictEqual(true);
const title = wrapper.find('.card__title');
assert.ok(title);
assert.strictEqual(title.text(), 'Test');
expect(title).toHaveLength(1);
expect(title.text()).toStrictEqual('Test');
const child = wrapper.find('.child-test-class');
assert.ok(child);
assert.strictEqual(child.text(), 'Child');
expect(child).toHaveLength(1);
expect(child.text()).toStrictEqual('Child');
});
});

View File

@ -1,26 +1,25 @@
import assert from 'assert';
import React from 'react';
import { shallow } from 'enzyme';
import Confusable from './confusable.component';
describe('Confusable component', function () {
it('should detect zero-width unicode', function () {
describe('Confusable component', () => {
it('should detect zero-width unicode', () => {
const wrapper = shallow(<Confusable input="vitalik.eth" />);
assert.ok(wrapper.find('.confusable__point').length === 1);
expect(wrapper.find('.confusable__point')).toHaveLength(1);
});
it('should detect homoglyphic unicode points', function () {
it('should detect homoglyphic unicode points', () => {
const wrapper = shallow(<Confusable input="faceboоk.eth" />);
assert.ok(wrapper.find('.confusable__point').length === 1);
expect(wrapper.find('.confusable__point')).toHaveLength(1);
});
it('should detect multiple homoglyphic unicode points', function () {
it('should detect multiple homoglyphic unicode points', () => {
const wrapper = shallow(<Confusable input="ѕсоре.eth" />);
assert.ok(wrapper.find('.confusable__point').length === 5);
expect(wrapper.find('.confusable__point')).toHaveLength(5);
});
it('should not detect emoji', function () {
it('should not detect emoji', () => {
const wrapper = shallow(<Confusable input="👻.eth" />);
assert.ok(wrapper.find('.confusable__point').length === 0);
expect(wrapper.find('.confusable__point')).toHaveLength(0);
});
});

View File

@ -1,12 +1,11 @@
import assert from 'assert';
import React from 'react';
import { shallow } from 'enzyme';
import sinon from 'sinon';
import * as reactRedux from 'react-redux';
import CurrencyDisplay from './currency-display.component';
describe('CurrencyDisplay Component', function () {
beforeEach(function () {
describe('CurrencyDisplay Component', () => {
beforeEach(() => {
const stub = sinon.stub(reactRedux, 'useSelector');
stub.callsFake(() => ({
currentCurrency: 'usd',
@ -14,7 +13,10 @@ describe('CurrencyDisplay Component', function () {
conversionRate: 280.45,
}));
});
it('should render text with a className', function () {
afterEach(() => {
sinon.restore();
});
it('should render text with a className', () => {
const wrapper = shallow(
<CurrencyDisplay
displayValue="$123.45"
@ -23,11 +25,11 @@ describe('CurrencyDisplay Component', function () {
/>,
);
assert.ok(wrapper.hasClass('currency-display'));
assert.strictEqual(wrapper.text(), '$123.45');
expect(wrapper.hasClass('currency-display')).toStrictEqual(true);
expect(wrapper.text()).toStrictEqual('$123.45');
});
it('should render text with a prefix', function () {
it('should render text with a prefix', () => {
const wrapper = shallow(
<CurrencyDisplay
displayValue="$123.45"
@ -37,10 +39,7 @@ describe('CurrencyDisplay Component', function () {
/>,
);
assert.ok(wrapper.hasClass('currency-display'));
assert.strictEqual(wrapper.text(), '-$123.45');
});
afterEach(function () {
sinon.restore();
expect(wrapper.hasClass('currency-display')).toStrictEqual(true);
expect(wrapper.text()).toStrictEqual('-$123.45');
});
});

View File

@ -1,4 +1,3 @@
import assert from 'assert';
import React from 'react';
import PropTypes from 'prop-types';
import { shallow, mount } from 'enzyme';
@ -9,16 +8,16 @@ import UnitInput from '../unit-input';
import CurrencyDisplay from '../currency-display';
import CurrencyInput from './currency-input.component';
describe('CurrencyInput Component', function () {
describe('rendering', function () {
it('should render properly without a suffix', function () {
describe('CurrencyInput Component', () => {
describe('rendering', () => {
it('should render properly without a suffix', () => {
const wrapper = shallow(<CurrencyInput />);
assert.ok(wrapper);
assert.strictEqual(wrapper.find(UnitInput).length, 1);
expect(wrapper).toHaveLength(1);
expect(wrapper.find(UnitInput)).toHaveLength(1);
});
it('should render properly with a suffix', function () {
it('should render properly with a suffix', () => {
const mockStore = {
metamask: {
nativeCurrency: 'ETH',
@ -38,13 +37,13 @@ describe('CurrencyInput Component', function () {
</Provider>,
);
assert.ok(wrapper);
assert.strictEqual(wrapper.find('.unit-input__suffix').length, 1);
assert.strictEqual(wrapper.find('.unit-input__suffix').text(), 'ETH');
assert.strictEqual(wrapper.find(CurrencyDisplay).length, 1);
expect(wrapper).toHaveLength(1);
expect(wrapper.find('.unit-input__suffix')).toHaveLength(1);
expect(wrapper.find('.unit-input__suffix').text()).toStrictEqual('ETH');
expect(wrapper.find(CurrencyDisplay)).toHaveLength(1);
});
it('should render properly with an ETH value', function () {
it('should render properly with an ETH value', () => {
const mockStore = {
metamask: {
nativeCurrency: 'ETH',
@ -67,26 +66,24 @@ describe('CurrencyInput Component', function () {
</Provider>,
);
assert.ok(wrapper);
expect(wrapper).toHaveLength(1);
const currencyInputInstance = wrapper
.find(CurrencyInput)
.at(0)
.instance();
assert.strictEqual(currencyInputInstance.state.decimalValue, 1);
assert.strictEqual(
currencyInputInstance.state.hexValue,
expect(currencyInputInstance.state.decimalValue).toStrictEqual(1);
expect(currencyInputInstance.state.hexValue).toStrictEqual(
'de0b6b3a7640000',
);
assert.strictEqual(wrapper.find('.unit-input__suffix').length, 1);
assert.strictEqual(wrapper.find('.unit-input__suffix').text(), 'ETH');
assert.strictEqual(wrapper.find('.unit-input__input').props().value, 1);
assert.strictEqual(
wrapper.find('.currency-display-component').text(),
expect(wrapper.find('.unit-input__suffix')).toHaveLength(1);
expect(wrapper.find('.unit-input__suffix').text()).toStrictEqual('ETH');
expect(wrapper.find('.unit-input__input').props().value).toStrictEqual(1);
expect(wrapper.find('.currency-display-component').text()).toStrictEqual(
'$231.06USD',
);
});
it('should render properly with a fiat value', function () {
it('should render properly with a fiat value', () => {
const mockStore = {
metamask: {
nativeCurrency: 'ETH',
@ -110,23 +107,24 @@ describe('CurrencyInput Component', function () {
</Provider>,
);
assert.ok(wrapper);
expect(wrapper).toHaveLength(1);
const currencyInputInstance = wrapper
.find(CurrencyInput)
.at(0)
.instance();
assert.strictEqual(currencyInputInstance.state.decimalValue, 1);
assert.strictEqual(currencyInputInstance.state.hexValue, 'f602f2234d0ea');
assert.strictEqual(wrapper.find('.unit-input__suffix').length, 1);
assert.strictEqual(wrapper.find('.unit-input__suffix').text(), 'USD');
assert.strictEqual(wrapper.find('.unit-input__input').props().value, 1);
assert.strictEqual(
wrapper.find('.currency-display-component').text(),
expect(currencyInputInstance.state.decimalValue).toStrictEqual(1);
expect(currencyInputInstance.state.hexValue).toStrictEqual(
'f602f2234d0ea',
);
expect(wrapper.find('.unit-input__suffix')).toHaveLength(1);
expect(wrapper.find('.unit-input__suffix').text()).toStrictEqual('USD');
expect(wrapper.find('.unit-input__input').props().value).toStrictEqual(1);
expect(wrapper.find('.currency-display-component').text()).toStrictEqual(
'0.004328ETH',
);
});
it('should render properly with a native value when hideFiat is true', function () {
it('should render properly with a native value when hideFiat is true', () => {
const mockStore = {
metamask: {
nativeCurrency: 'ETH',
@ -134,6 +132,7 @@ describe('CurrencyInput Component', function () {
conversionRate: 231.06,
},
};
const store = configureMockStore()(mockStore);
const wrapper = mount(
@ -155,36 +154,36 @@ describe('CurrencyInput Component', function () {
},
);
assert.ok(wrapper);
expect(wrapper).toHaveLength(1);
const currencyInputInstance = wrapper
.find(CurrencyInput)
.at(0)
.instance();
assert.strictEqual(currencyInputInstance.state.decimalValue, 0.004328);
assert.strictEqual(currencyInputInstance.state.hexValue, 'f602f2234d0ea');
assert.strictEqual(wrapper.find('.unit-input__suffix').length, 1);
assert.strictEqual(wrapper.find('.unit-input__suffix').text(), 'ETH');
assert.strictEqual(
wrapper.find('.unit-input__input').props().value,
expect(currencyInputInstance.state.decimalValue).toStrictEqual(0.004328);
expect(currencyInputInstance.state.hexValue).toStrictEqual(
'f602f2234d0ea',
);
expect(wrapper.find('.unit-input__suffix')).toHaveLength(1);
expect(wrapper.find('.unit-input__suffix').text()).toStrictEqual('ETH');
expect(wrapper.find('.unit-input__input').props().value).toStrictEqual(
0.004328,
);
assert.strictEqual(
expect(
wrapper.find('.currency-input__conversion-component').text(),
'noConversionRateAvailable_t',
);
).toStrictEqual('noConversionRateAvailable_t');
});
});
describe('handling actions', function () {
describe('handling actions', () => {
const handleChangeSpy = sinon.spy();
const handleBlurSpy = sinon.spy();
afterEach(function () {
afterEach(() => {
handleChangeSpy.resetHistory();
handleBlurSpy.resetHistory();
});
it('should call onChange on input changes with the hex value for ETH', function () {
it('should call onChange on input changes with the hex value for ETH', () => {
const mockStore = {
metamask: {
nativeCurrency: 'ETH',
@ -205,38 +204,35 @@ describe('CurrencyInput Component', function () {
</Provider>,
);
assert.ok(wrapper);
assert.strictEqual(handleChangeSpy.callCount, 0);
assert.strictEqual(handleBlurSpy.callCount, 0);
expect(wrapper).toHaveLength(1);
expect(handleChangeSpy.callCount).toStrictEqual(0);
expect(handleBlurSpy.callCount).toStrictEqual(0);
const currencyInputInstance = wrapper
.find(CurrencyInput)
.at(0)
.instance();
assert.strictEqual(currencyInputInstance.state.decimalValue, 0);
assert.strictEqual(currencyInputInstance.state.hexValue, undefined);
assert.strictEqual(
wrapper.find('.currency-display-component').text(),
expect(currencyInputInstance.state.decimalValue).toStrictEqual(0);
expect(currencyInputInstance.state.hexValue).toBeUndefined();
expect(wrapper.find('.currency-display-component').text()).toStrictEqual(
'$0.00USD',
);
const input = wrapper.find('input');
assert.strictEqual(input.props().value, 0);
expect(input.props().value).toStrictEqual(0);
input.simulate('change', { target: { value: 1 } });
assert.strictEqual(handleChangeSpy.callCount, 1);
assert.ok(handleChangeSpy.calledWith('de0b6b3a7640000'));
assert.strictEqual(
wrapper.find('.currency-display-component').text(),
expect(handleChangeSpy.callCount).toStrictEqual(1);
expect(handleChangeSpy.calledWith('de0b6b3a7640000')).toStrictEqual(true);
expect(wrapper.find('.currency-display-component').text()).toStrictEqual(
'$231.06USD',
);
assert.strictEqual(currencyInputInstance.state.decimalValue, 1);
assert.strictEqual(
currencyInputInstance.state.hexValue,
expect(currencyInputInstance.state.decimalValue).toStrictEqual(1);
expect(currencyInputInstance.state.hexValue).toStrictEqual(
'de0b6b3a7640000',
);
});
it('should call onChange on input changes with the hex value for fiat', function () {
it('should call onChange on input changes with the hex value for fiat', () => {
const mockStore = {
metamask: {
nativeCurrency: 'ETH',
@ -258,35 +254,35 @@ describe('CurrencyInput Component', function () {
</Provider>,
);
assert.ok(wrapper);
assert.strictEqual(handleChangeSpy.callCount, 0);
assert.strictEqual(handleBlurSpy.callCount, 0);
expect(wrapper).toHaveLength(1);
expect(handleChangeSpy.callCount).toStrictEqual(0);
expect(handleBlurSpy.callCount).toStrictEqual(0);
const currencyInputInstance = wrapper
.find(CurrencyInput)
.at(0)
.instance();
assert.strictEqual(currencyInputInstance.state.decimalValue, 0);
assert.strictEqual(currencyInputInstance.state.hexValue, undefined);
assert.strictEqual(
wrapper.find('.currency-display-component').text(),
expect(currencyInputInstance.state.decimalValue).toStrictEqual(0);
expect(currencyInputInstance.state.hexValue).toBeUndefined();
expect(wrapper.find('.currency-display-component').text()).toStrictEqual(
'0ETH',
);
const input = wrapper.find('input');
assert.strictEqual(input.props().value, 0);
expect(input.props().value).toStrictEqual(0);
input.simulate('change', { target: { value: 1 } });
assert.strictEqual(handleChangeSpy.callCount, 1);
assert.ok(handleChangeSpy.calledWith('f602f2234d0ea'));
assert.strictEqual(
wrapper.find('.currency-display-component').text(),
expect(handleChangeSpy.callCount).toStrictEqual(1);
expect(handleChangeSpy.calledWith('f602f2234d0ea')).toStrictEqual(true);
expect(wrapper.find('.currency-display-component').text()).toStrictEqual(
'0.004328ETH',
);
assert.strictEqual(currencyInputInstance.state.decimalValue, 1);
assert.strictEqual(currencyInputInstance.state.hexValue, 'f602f2234d0ea');
expect(currencyInputInstance.state.decimalValue).toStrictEqual(1);
expect(currencyInputInstance.state.hexValue).toStrictEqual(
'f602f2234d0ea',
);
});
it('should change the state and pass in a new decimalValue when props.value changes', function () {
it('should change the state and pass in a new decimalValue when props.value changes', () => {
const mockStore = {
metamask: {
nativeCurrency: 'ETH',
@ -308,29 +304,26 @@ describe('CurrencyInput Component', function () {
</Provider>,
);
assert.ok(wrapper);
expect(wrapper).toHaveLength(1);
const currencyInputInstance = wrapper.find(CurrencyInput).dive();
assert.strictEqual(currencyInputInstance.state('decimalValue'), 0);
assert.strictEqual(currencyInputInstance.state('hexValue'), undefined);
assert.strictEqual(
currencyInputInstance.find(UnitInput).props().value,
expect(currencyInputInstance.state('decimalValue')).toStrictEqual(0);
expect(currencyInputInstance.state('hexValue')).toBeUndefined();
expect(currencyInputInstance.find(UnitInput).props().value).toStrictEqual(
0,
);
currencyInputInstance.setProps({ value: '1ec05e43e72400' });
currencyInputInstance.update();
assert.strictEqual(currencyInputInstance.state('decimalValue'), 2);
assert.strictEqual(
currencyInputInstance.state('hexValue'),
expect(currencyInputInstance.state('decimalValue')).toStrictEqual(2);
expect(currencyInputInstance.state('hexValue')).toStrictEqual(
'1ec05e43e72400',
);
assert.strictEqual(
currencyInputInstance.find(UnitInput).props().value,
expect(currencyInputInstance.find(UnitInput).props().value).toStrictEqual(
2,
);
});
it('should swap selected currency when swap icon is clicked', function () {
it('should swap selected currency when swap icon is clicked', () => {
const mockStore = {
metamask: {
nativeCurrency: 'ETH',
@ -352,40 +345,36 @@ describe('CurrencyInput Component', function () {
</Provider>,
);
assert.ok(wrapper);
assert.strictEqual(handleChangeSpy.callCount, 0);
assert.strictEqual(handleBlurSpy.callCount, 0);
expect(wrapper).toHaveLength(1);
expect(handleChangeSpy.callCount).toStrictEqual(0);
expect(handleBlurSpy.callCount).toStrictEqual(0);
const currencyInputInstance = wrapper
.find(CurrencyInput)
.at(0)
.instance();
assert.strictEqual(currencyInputInstance.state.decimalValue, 0);
assert.strictEqual(currencyInputInstance.state.hexValue, undefined);
assert.strictEqual(
wrapper.find('.currency-display-component').text(),
expect(currencyInputInstance.state.decimalValue).toStrictEqual(0);
expect(currencyInputInstance.state.hexValue).toBeUndefined();
expect(wrapper.find('.currency-display-component').text()).toStrictEqual(
'$0.00USD',
);
const input = wrapper.find('input');
assert.strictEqual(input.props().value, 0);
expect(input.props().value).toStrictEqual(0);
input.simulate('change', { target: { value: 1 } });
assert.strictEqual(handleChangeSpy.callCount, 1);
assert.ok(handleChangeSpy.calledWith('de0b6b3a7640000'));
assert.strictEqual(
wrapper.find('.currency-display-component').text(),
expect(handleChangeSpy.callCount).toStrictEqual(1);
expect(handleChangeSpy.calledWith('de0b6b3a7640000')).toStrictEqual(true);
expect(wrapper.find('.currency-display-component').text()).toStrictEqual(
'$231.06USD',
);
assert.strictEqual(currencyInputInstance.state.decimalValue, 1);
assert.strictEqual(
currencyInputInstance.state.hexValue,
expect(currencyInputInstance.state.decimalValue).toStrictEqual(1);
expect(currencyInputInstance.state.hexValue).toStrictEqual(
'de0b6b3a7640000',
);
const swap = wrapper.find('.currency-input__swap-component');
swap.simulate('click');
assert.strictEqual(
wrapper.find('.currency-display-component').text(),
expect(wrapper.find('.currency-display-component').text()).toStrictEqual(
'0.004328ETH',
);
});

View File

@ -1,20 +1,18 @@
import assert from 'assert';
import proxyquire from 'proxyquire';
// eslint-disable-next-line import/unambiguous
let mapStateToProps, mergeProps;
proxyquire('./currency-input.container.js', {
'react-redux': {
connect: (ms, _, mp) => {
mapStateToProps = ms;
mergeProps = mp;
return () => ({});
},
jest.mock('react-redux', () => ({
connect: (ms, _, mp) => {
mapStateToProps = ms;
mergeProps = mp;
return () => ({});
},
});
}));
describe('CurrencyInput container', function () {
describe('mapStateToProps()', function () {
require('./currency-input.container.js');
describe('CurrencyInput container', () => {
describe('mapStateToProps()', () => {
const tests = [
// Test # 1
{
@ -115,13 +113,13 @@ describe('CurrencyInput container', function () {
];
tests.forEach(({ mockState, expected, comment }) => {
it(comment, function () {
return assert.deepStrictEqual(mapStateToProps(mockState), expected);
it(`${comment}`, () => {
expect(mapStateToProps(mockState)).toStrictEqual(expected);
});
});
});
describe('mergeProps()', function () {
describe('mergeProps()', () => {
const tests = [
// Test # 1
{
@ -173,9 +171,8 @@ describe('CurrencyInput container', function () {
expected,
comment,
}) => {
it(comment, function () {
assert.deepStrictEqual(
mergeProps(stateProps, dispatchProps, ownProps),
it(`${comment}`, () => {
expect(mergeProps(stateProps, dispatchProps, ownProps)).toStrictEqual(
expected,
);
});

View File

@ -1,35 +1,32 @@
import assert from 'assert';
import React from 'react';
import { shallow } from 'enzyme';
import ErrorMessage from './error-message.component';
describe('ErrorMessage Component', function () {
describe('ErrorMessage Component', () => {
const t = (key) => `translate ${key}`;
it('should render a message from props.errorMessage', function () {
it('should render a message from props.errorMessage', () => {
const wrapper = shallow(<ErrorMessage errorMessage="This is an error." />, {
context: { t },
});
assert.ok(wrapper);
assert.strictEqual(wrapper.find('.error-message').length, 1);
assert.strictEqual(wrapper.find('.error-message__icon').length, 1);
assert.strictEqual(
wrapper.find('.error-message__text').text(),
expect(wrapper).toHaveLength(1);
expect(wrapper.find('.error-message')).toHaveLength(1);
expect(wrapper.find('.error-message__icon')).toHaveLength(1);
expect(wrapper.find('.error-message__text').text()).toStrictEqual(
'ALERT: This is an error.',
);
});
it('should render a message translated from props.errorKey', function () {
it('should render a message translated from props.errorKey', () => {
const wrapper = shallow(<ErrorMessage errorKey="testKey" />, {
context: { t },
});
assert.ok(wrapper);
assert.strictEqual(wrapper.find('.error-message').length, 1);
assert.strictEqual(wrapper.find('.error-message__icon').length, 1);
assert.strictEqual(
wrapper.find('.error-message__text').text(),
expect(wrapper).toHaveLength(1);
expect(wrapper.find('.error-message')).toHaveLength(1);
expect(wrapper.find('.error-message__icon')).toHaveLength(1);
expect(wrapper.find('.error-message__text').text()).toStrictEqual(
'ALERT: translate testKey',
);
});

View File

@ -1,24 +1,23 @@
import assert from 'assert';
import React from 'react';
import { shallow } from 'enzyme';
import HexToDecimal from './hex-to-decimal.component';
describe('HexToDecimal Component', function () {
it('should render a prefixed hex as a decimal with a className', function () {
describe('HexToDecimal Component', () => {
it('should render a prefixed hex as a decimal with a className', () => {
const wrapper = shallow(
<HexToDecimal value="0x3039" className="hex-to-decimal" />,
);
assert.ok(wrapper.hasClass('hex-to-decimal'));
assert.strictEqual(wrapper.text(), '12345');
expect(wrapper.hasClass('hex-to-decimal')).toStrictEqual(true);
expect(wrapper.text()).toStrictEqual('12345');
});
it('should render an unprefixed hex as a decimal with a className', function () {
it('should render an unprefixed hex as a decimal with a className', () => {
const wrapper = shallow(
<HexToDecimal value="1A85" className="hex-to-decimal" />,
);
assert.ok(wrapper.hasClass('hex-to-decimal'));
assert.strictEqual(wrapper.text(), '6789');
expect(wrapper.hasClass('hex-to-decimal')).toStrictEqual(true);
expect(wrapper.text()).toStrictEqual('6789');
});
});

View File

@ -1,11 +1,10 @@
import assert from 'assert';
import React from 'react';
import thunk from 'redux-thunk';
import configureMockStore from 'redux-mock-store';
import { mount } from 'enzyme';
import Identicon from './identicon.component';
describe('Identicon', function () {
describe('Identicon', () => {
const state = {
metamask: {
useBlockie: false,
@ -16,34 +15,33 @@ describe('Identicon', function () {
const mockStore = configureMockStore(middlewares);
const store = mockStore(state);
it('renders empty identicon with no props', function () {
it('renders empty identicon with no props', () => {
const wrapper = mount(<Identicon store={store} />);
assert.ok(wrapper.find('div'), 'Empty identicon found');
expect(wrapper.find('div').prop('className')).toStrictEqual(
'identicon__image-border',
);
});
it('renders custom image and add className props', function () {
it('renders custom image and add className props', () => {
const wrapper = mount(
<Identicon store={store} className="test-image" image="test-image" />,
);
assert.strictEqual(
wrapper.find('img.test-image').prop('className'),
expect(wrapper.find('img.test-image').prop('className')).toStrictEqual(
'identicon test-image',
);
assert.strictEqual(
wrapper.find('img.test-image').prop('src'),
expect(wrapper.find('img.test-image').prop('src')).toStrictEqual(
'test-image',
);
});
it('renders div with address prop', function () {
it('renders div with address prop', () => {
const wrapper = mount(
<Identicon store={store} className="test-address" address="0xTest" />,
);
assert.strictEqual(
wrapper.find('div.test-address').prop('className'),
expect(wrapper.find('div.test-address').prop('className')).toStrictEqual(
'identicon test-address',
);
});

View File

@ -1,7 +1,6 @@
import assert from 'assert';
import { shallow } from 'enzyme';
import React from 'react';
import Sinon from 'sinon';
import sinon from 'sinon';
import Preloader from '../icon/preloader/preloader-icon.component';
import Send from '../icon/send-icon.component';
import ListItem from './list-item.component';
@ -13,11 +12,11 @@ const RIGHT_CONTENT = <p>Content rendered to the right</p>;
const CHILDREN = <button>I am a button</button>;
const MID_CONTENT = <p>Content rendered in the middle</p>;
describe('ListItem', function () {
describe('ListItem', () => {
let wrapper;
let clickHandler;
before(function () {
clickHandler = Sinon.fake();
beforeAll(() => {
clickHandler = sinon.fake();
wrapper = shallow(
<ListItem
className={CLASSNAME}
@ -26,59 +25,56 @@ describe('ListItem', function () {
subtitle={SUBTITLE}
rightContent={RIGHT_CONTENT}
midContent={MID_CONTENT}
icon={<Send />}
titleIcon={<Preloader />}
icon={<Send size={28} color="2F80ED" />}
titleIcon={<Preloader size={28} />}
onClick={clickHandler}
>
{CHILDREN}
</ListItem>,
);
});
it('includes the data-testid', function () {
assert.strictEqual(wrapper.props()['data-testid'], 'test-id');
afterAll(() => {
sinon.restore();
});
it(`renders "${TITLE}" title`, function () {
assert.strictEqual(wrapper.find('.list-item__heading h2').text(), TITLE);
it('includes the data-testid', () => {
expect(wrapper.props()['data-testid']).toStrictEqual('test-id');
});
it(`renders "I am a list item" subtitle`, function () {
assert.strictEqual(
wrapper.find('.list-item__subheading').text(),
it(`renders "${TITLE}" title`, () => {
expect(wrapper.find('.list-item__heading h2').text()).toStrictEqual(TITLE);
});
it(`renders "I am a list item" subtitle`, () => {
expect(wrapper.find('.list-item__subheading').text()).toStrictEqual(
'I am a list item',
);
});
it('attaches external className', function () {
assert(wrapper.props().className.includes(CLASSNAME));
it('attaches external className', () => {
expect(wrapper.props().className).toContain(CLASSNAME);
});
it('renders content on the right side of the list item', function () {
assert.strictEqual(
wrapper.find('.list-item__right-content p').text(),
it('renders content on the right side of the list item', () => {
expect(wrapper.find('.list-item__right-content p').text()).toStrictEqual(
'Content rendered to the right',
);
});
it('renders content in the middle of the list item', function () {
assert.strictEqual(
wrapper.find('.list-item__mid-content p').text(),
it('renders content in the middle of the list item', () => {
expect(wrapper.find('.list-item__mid-content p').text()).toStrictEqual(
'Content rendered in the middle',
);
});
it('renders list item actions', function () {
assert.strictEqual(
wrapper.find('.list-item__actions button').text(),
it('renders list item actions', () => {
expect(wrapper.find('.list-item__actions button').text()).toStrictEqual(
'I am a button',
);
});
it('renders the title icon', function () {
assert(wrapper.find(Preloader));
it('renders the title icon', () => {
expect(wrapper.find(Preloader)).toHaveLength(1);
});
it('renders the list item icon', function () {
assert(wrapper.find(Send));
it('renders the list item icon', () => {
expect(wrapper.find(Send)).toHaveLength(1);
});
it('handles click action and fires onClick', function () {
it('handles click action and fires onClick', () => {
wrapper.simulate('click');
assert.strictEqual(clickHandler.callCount, 1);
});
after(function () {
Sinon.restore();
expect(clickHandler.callCount).toStrictEqual(1);
});
});

View File

@ -1,32 +1,27 @@
import assert from 'assert';
import React from 'react';
import { mount } from 'enzyme';
import MetaFoxLogo from '.';
describe('MetaFoxLogo', function () {
it('sets icon height and width to 42 by default', function () {
describe('MetaFoxLogo', () => {
it('sets icon height and width to 42 by default', () => {
const wrapper = mount(<MetaFoxLogo />);
assert.strictEqual(
expect(
wrapper.find('img.app-header__metafox-logo--icon').prop('width'),
42,
);
assert.strictEqual(
).toStrictEqual(42);
expect(
wrapper.find('img.app-header__metafox-logo--icon').prop('height'),
42,
);
).toStrictEqual(42);
});
it('does not set icon height and width when unsetIconHeight is true', function () {
it('does not set icon height and width when unsetIconHeight is true', () => {
const wrapper = mount(<MetaFoxLogo unsetIconHeight />);
assert.strictEqual(
expect(
wrapper.find('img.app-header__metafox-logo--icon').prop('width'),
undefined,
);
assert.strictEqual(
).toBeUndefined();
expect(
wrapper.find('img.app-header__metafox-logo--icon').prop('height'),
undefined,
);
).toBeUndefined();
});
});

View File

@ -1,16 +1,15 @@
import assert from 'assert';
import React from 'react';
import { shallow } from 'enzyme';
import sinon from 'sinon';
import Button from '../../button';
import PageFooter from './page-container-footer.component';
describe('Page Footer', function () {
describe('Page Footer', () => {
let wrapper;
const onCancel = sinon.spy();
const onSubmit = sinon.spy();
beforeEach(function () {
beforeEach(() => {
wrapper = shallow(
<PageFooter
onCancel={onCancel}
@ -23,11 +22,11 @@ describe('Page Footer', function () {
);
});
it('renders page container footer', function () {
assert.strictEqual(wrapper.find('.page-container__footer').length, 1);
it('renders page container footer', () => {
expect(wrapper.find('.page-container__footer')).toHaveLength(1);
});
it('should render a secondary footer inside page-container__footer when given children', function () {
it('should render a secondary footer inside page-container__footer when given children', () => {
wrapper = shallow(
<PageFooter>
<div>Works</div>
@ -35,62 +34,54 @@ describe('Page Footer', function () {
{ context: { t: sinon.spy((k) => `[${k}]`) } },
);
assert.strictEqual(
wrapper.find('.page-container__footer-secondary').length,
1,
);
expect(wrapper.find('.page-container__footer-secondary')).toHaveLength(1);
});
it('renders two button components', function () {
assert.strictEqual(wrapper.find(Button).length, 2);
it('renders two button components', () => {
expect(wrapper.find(Button)).toHaveLength(2);
});
describe('Cancel Button', function () {
it('has button type of default', function () {
assert.strictEqual(
describe('Cancel Button', () => {
it('has button type of default', () => {
expect(
wrapper.find('.page-container__footer-button').first().prop('type'),
'default',
);
).toStrictEqual('default');
});
it('has children text of Cancel', function () {
assert.strictEqual(
it('has children text of Cancel', () => {
expect(
wrapper.find('.page-container__footer-button').first().prop('children'),
'Cancel',
);
).toStrictEqual('Cancel');
});
it('should call cancel when click is simulated', function () {
it('should call cancel when click is simulated', () => {
wrapper.find('.page-container__footer-button').first().prop('onClick')();
assert.strictEqual(onCancel.callCount, 1);
expect(onCancel.callCount).toStrictEqual(1);
});
});
describe('Submit Button', function () {
it('assigns button type based on props', function () {
assert.strictEqual(
describe('Submit Button', () => {
it('assigns button type based on props', () => {
expect(
wrapper.find('.page-container__footer-button').last().prop('type'),
'Test Type',
);
).toStrictEqual('Test Type');
});
it('has disabled prop', function () {
assert.strictEqual(
it('has disabled prop', () => {
expect(
wrapper.find('.page-container__footer-button').last().prop('disabled'),
false,
);
).toStrictEqual(false);
});
it('has children text when submitText prop exists', function () {
assert.strictEqual(
it('has children text when submitText prop exists', () => {
expect(
wrapper.find('.page-container__footer-button').last().prop('children'),
'Submit',
);
).toStrictEqual('Submit');
});
it('should call submit when click is simulated', function () {
it('should call submit when click is simulated', () => {
wrapper.find('.page-container__footer-button').last().prop('onClick')();
assert.strictEqual(onSubmit.callCount, 1);
expect(onSubmit.callCount).toStrictEqual(1);
});
});
});

View File

@ -1,13 +1,12 @@
import assert from 'assert';
import React from 'react';
import { shallow } from 'enzyme';
import sinon from 'sinon';
import PageContainerHeader from './page-container-header.component';
describe('Page Container Header', function () {
describe('Page Container Header', () => {
let wrapper, style, onBackButtonClick, onClose;
beforeEach(function () {
beforeEach(() => {
style = { test: 'style' };
onBackButtonClick = sinon.spy();
onClose = sinon.spy();
@ -25,35 +24,30 @@ describe('Page Container Header', function () {
);
});
describe('Render Header Row', function () {
it('renders back button', function () {
assert.strictEqual(
wrapper.find('.page-container__back-button').length,
1,
);
assert.strictEqual(
wrapper.find('.page-container__back-button').text(),
describe('Render Header Row', () => {
it('renders back button', () => {
expect(wrapper.find('.page-container__back-button')).toHaveLength(1);
expect(wrapper.find('.page-container__back-button').text()).toStrictEqual(
'Back',
);
});
it('ensures style prop', function () {
assert.strictEqual(
it('ensures style prop', () => {
expect(
wrapper.find('.page-container__back-button').props().style,
style,
);
).toStrictEqual(style);
});
it('should call back button when click is simulated', function () {
it('should call back button when click is simulated', () => {
wrapper.find('.page-container__back-button').prop('onClick')();
assert.strictEqual(onBackButtonClick.callCount, 1);
expect(onBackButtonClick.callCount).toStrictEqual(1);
});
});
describe('Render', function () {
describe('Render', () => {
let header, headerRow, pageTitle, pageSubtitle, pageClose, pageTab;
beforeEach(function () {
beforeEach(() => {
header = wrapper.find('.page-container__header--no-padding-bottom');
headerRow = wrapper.find('.page-container__header-row');
pageTitle = wrapper.find('.page-container__title');
@ -62,30 +56,30 @@ describe('Page Container Header', function () {
pageTab = wrapper.find('.page-container__tabs');
});
it('renders page container', function () {
assert.strictEqual(header.length, 1);
assert.strictEqual(headerRow.length, 1);
assert.strictEqual(pageTitle.length, 1);
assert.strictEqual(pageSubtitle.length, 1);
assert.strictEqual(pageClose.length, 1);
assert.strictEqual(pageTab.length, 1);
it('renders page container', () => {
expect(header).toHaveLength(1);
expect(headerRow).toHaveLength(1);
expect(pageTitle).toHaveLength(1);
expect(pageSubtitle).toHaveLength(1);
expect(pageClose).toHaveLength(1);
expect(pageTab).toHaveLength(1);
});
it('renders title', function () {
assert.strictEqual(pageTitle.text(), 'Test Title');
it('renders title', () => {
expect(pageTitle.text()).toStrictEqual('Test Title');
});
it('renders subtitle', function () {
assert.strictEqual(pageSubtitle.text(), 'Test Subtitle');
it('renders subtitle', () => {
expect(pageSubtitle.text()).toStrictEqual('Test Subtitle');
});
it('renders tabs', function () {
assert.strictEqual(pageTab.text(), 'Test Tab');
it('renders tabs', () => {
expect(pageTab.text()).toStrictEqual('Test Tab');
});
it('should call close when click is simulated', function () {
it('should call close when click is simulated', () => {
pageClose.prop('onClick')();
assert.strictEqual(onClose.callCount, 1);
expect(onClose.callCount).toStrictEqual(1);
});
});
});

View File

@ -1,4 +1,3 @@
import assert from 'assert';
import React from 'react';
import PropTypes from 'prop-types';
import { shallow, mount } from 'enzyme';
@ -9,11 +8,11 @@ import UnitInput from '../unit-input';
import CurrencyDisplay from '../currency-display';
import TokenInput from './token-input.component';
describe('TokenInput Component', function () {
describe('TokenInput Component', () => {
const t = (key) => `translate ${key}`;
describe('rendering', function () {
it('should render properly', function () {
describe('rendering', () => {
it('should render properly', () => {
const mockStore = {
metamask: {
currentCurrency: 'usd',
@ -40,20 +39,18 @@ describe('TokenInput Component', function () {
},
);
assert.ok(wrapper);
assert.strictEqual(wrapper.find('.unit-input__suffix').length, 1);
assert.strictEqual(wrapper.find('.unit-input__suffix').text(), 'ABC');
assert.strictEqual(
wrapper.find('.currency-input__conversion-component').length,
1,
);
assert.strictEqual(
expect(wrapper).toHaveLength(1);
expect(wrapper.find('.unit-input__suffix')).toHaveLength(1);
expect(wrapper.find('.unit-input__suffix').text()).toStrictEqual('ABC');
expect(
wrapper.find('.currency-input__conversion-component'),
).toHaveLength(1);
expect(
wrapper.find('.currency-input__conversion-component').text(),
'translate noConversionRateAvailable',
);
).toStrictEqual('translate noConversionRateAvailable');
});
it('should render properly with tokenExchangeRates', function () {
it('should render properly with tokenExchangeRates', () => {
const mockStore = {
metamask: {
currentCurrency: 'usd',
@ -81,13 +78,13 @@ describe('TokenInput Component', function () {
},
);
assert.ok(wrapper);
assert.strictEqual(wrapper.find('.unit-input__suffix').length, 1);
assert.strictEqual(wrapper.find('.unit-input__suffix').text(), 'ABC');
assert.strictEqual(wrapper.find(CurrencyDisplay).length, 1);
expect(wrapper).toHaveLength(1);
expect(wrapper.find('.unit-input__suffix')).toHaveLength(1);
expect(wrapper.find('.unit-input__suffix').text()).toStrictEqual('ABC');
expect(wrapper.find(CurrencyDisplay)).toHaveLength(1);
});
it('should render properly with a token value for ETH', function () {
it('should render properly with a token value for ETH', () => {
const mockStore = {
metamask: {
currentCurrency: 'usd',
@ -110,20 +107,21 @@ describe('TokenInput Component', function () {
</Provider>,
);
assert.ok(wrapper);
expect(wrapper).toHaveLength(1);
const tokenInputInstance = wrapper.find(TokenInput).at(0).instance();
assert.strictEqual(tokenInputInstance.state.decimalValue, '1');
assert.strictEqual(tokenInputInstance.state.hexValue, '2710');
assert.strictEqual(wrapper.find('.unit-input__suffix').length, 1);
assert.strictEqual(wrapper.find('.unit-input__suffix').text(), 'ABC');
assert.strictEqual(wrapper.find('.unit-input__input').props().value, '1');
assert.strictEqual(
wrapper.find('.currency-display-component').text(),
expect(tokenInputInstance.state.decimalValue).toStrictEqual('1');
expect(tokenInputInstance.state.hexValue).toStrictEqual('2710');
expect(wrapper.find('.unit-input__suffix')).toHaveLength(1);
expect(wrapper.find('.unit-input__suffix').text()).toStrictEqual('ABC');
expect(wrapper.find('.unit-input__input').props().value).toStrictEqual(
'1',
);
expect(wrapper.find('.currency-display-component').text()).toStrictEqual(
'2ETH',
);
});
it('should render properly with a token value for fiat', function () {
it('should render properly with a token value for fiat', () => {
const mockStore = {
metamask: {
currentCurrency: 'usd',
@ -147,20 +145,21 @@ describe('TokenInput Component', function () {
</Provider>,
);
assert.ok(wrapper);
expect(wrapper).toHaveLength(1);
const tokenInputInstance = wrapper.find(TokenInput).at(0).instance();
assert.strictEqual(tokenInputInstance.state.decimalValue, '1');
assert.strictEqual(tokenInputInstance.state.hexValue, '2710');
assert.strictEqual(wrapper.find('.unit-input__suffix').length, 1);
assert.strictEqual(wrapper.find('.unit-input__suffix').text(), 'ABC');
assert.strictEqual(wrapper.find('.unit-input__input').props().value, '1');
assert.strictEqual(
wrapper.find('.currency-display-component').text(),
expect(tokenInputInstance.state.decimalValue).toStrictEqual('1');
expect(tokenInputInstance.state.hexValue).toStrictEqual('2710');
expect(wrapper.find('.unit-input__suffix')).toHaveLength(1);
expect(wrapper.find('.unit-input__suffix').text()).toStrictEqual('ABC');
expect(wrapper.find('.unit-input__input').props().value).toStrictEqual(
'1',
);
expect(wrapper.find('.currency-display-component').text()).toStrictEqual(
'$462.12USD',
);
});
it('should render properly with a token value for fiat, but hideConversion is true', function () {
it('should render properly with a token value for fiat, but hideConversion is true', () => {
const mockStore = {
metamask: {
currentCurrency: 'usd',
@ -191,30 +190,31 @@ describe('TokenInput Component', function () {
},
);
assert.ok(wrapper);
expect(wrapper).toHaveLength(1);
const tokenInputInstance = wrapper.find(TokenInput).at(0).instance();
assert.strictEqual(tokenInputInstance.state.decimalValue, '1');
assert.strictEqual(tokenInputInstance.state.hexValue, '2710');
assert.strictEqual(wrapper.find('.unit-input__suffix').length, 1);
assert.strictEqual(wrapper.find('.unit-input__suffix').text(), 'ABC');
assert.strictEqual(wrapper.find('.unit-input__input').props().value, '1');
assert.strictEqual(
wrapper.find('.currency-input__conversion-component').text(),
'translate noConversionRateAvailable',
expect(tokenInputInstance.state.decimalValue).toStrictEqual('1');
expect(tokenInputInstance.state.hexValue).toStrictEqual('2710');
expect(wrapper.find('.unit-input__suffix')).toHaveLength(1);
expect(wrapper.find('.unit-input__suffix').text()).toStrictEqual('ABC');
expect(wrapper.find('.unit-input__input').props().value).toStrictEqual(
'1',
);
expect(
wrapper.find('.currency-input__conversion-component').text(),
).toStrictEqual('translate noConversionRateAvailable');
});
});
describe('handling actions', function () {
describe('handling actions', () => {
const handleChangeSpy = sinon.spy();
const handleBlurSpy = sinon.spy();
afterEach(function () {
afterEach(() => {
handleChangeSpy.resetHistory();
handleBlurSpy.resetHistory();
});
it('should call onChange on input changes with the hex value for ETH', function () {
it('should call onChange on input changes with the hex value for ETH', () => {
const mockStore = {
metamask: {
currentCurrency: 'usd',
@ -236,32 +236,30 @@ describe('TokenInput Component', function () {
</Provider>,
);
assert.ok(wrapper);
assert.strictEqual(handleChangeSpy.callCount, 0);
assert.strictEqual(handleBlurSpy.callCount, 0);
expect(wrapper).toHaveLength(1);
expect(handleChangeSpy.callCount).toStrictEqual(0);
expect(handleBlurSpy.callCount).toStrictEqual(0);
const tokenInputInstance = wrapper.find(TokenInput).at(0).instance();
assert.strictEqual(tokenInputInstance.state.decimalValue, 0);
assert.strictEqual(tokenInputInstance.state.hexValue, undefined);
assert.strictEqual(
wrapper.find('.currency-display-component').text(),
expect(tokenInputInstance.state.decimalValue).toStrictEqual(0);
expect(tokenInputInstance.state.hexValue).toBeUndefined();
expect(wrapper.find('.currency-display-component').text()).toStrictEqual(
'0ETH',
);
const input = wrapper.find('input');
assert.strictEqual(input.props().value, 0);
expect(input.props().value).toStrictEqual(0);
input.simulate('change', { target: { value: 1 } });
assert.strictEqual(handleChangeSpy.callCount, 1);
assert.ok(handleChangeSpy.calledWith('2710'));
assert.strictEqual(
wrapper.find('.currency-display-component').text(),
expect(handleChangeSpy.callCount).toStrictEqual(1);
expect(handleChangeSpy.calledWith('2710')).toStrictEqual(true);
expect(wrapper.find('.currency-display-component').text()).toStrictEqual(
'2ETH',
);
assert.strictEqual(tokenInputInstance.state.decimalValue, 1);
assert.strictEqual(tokenInputInstance.state.hexValue, '2710');
expect(tokenInputInstance.state.decimalValue).toStrictEqual(1);
expect(tokenInputInstance.state.hexValue).toStrictEqual('2710');
});
it('should call onChange on input changes with the hex value for fiat', function () {
it('should call onChange on input changes with the hex value for fiat', () => {
const mockStore = {
metamask: {
currentCurrency: 'usd',
@ -284,32 +282,30 @@ describe('TokenInput Component', function () {
</Provider>,
);
assert.ok(wrapper);
assert.strictEqual(handleChangeSpy.callCount, 0);
assert.strictEqual(handleBlurSpy.callCount, 0);
expect(wrapper).toHaveLength(1);
expect(handleChangeSpy.callCount).toStrictEqual(0);
expect(handleBlurSpy.callCount).toStrictEqual(0);
const tokenInputInstance = wrapper.find(TokenInput).at(0).instance();
assert.strictEqual(tokenInputInstance.state.decimalValue, 0);
assert.strictEqual(tokenInputInstance.state.hexValue, undefined);
assert.strictEqual(
wrapper.find('.currency-display-component').text(),
expect(tokenInputInstance.state.decimalValue).toStrictEqual(0);
expect(tokenInputInstance.state.hexValue).toBeUndefined();
expect(wrapper.find('.currency-display-component').text()).toStrictEqual(
'$0.00USD',
);
const input = wrapper.find('input');
assert.strictEqual(input.props().value, 0);
expect(input.props().value).toStrictEqual(0);
input.simulate('change', { target: { value: 1 } });
assert.strictEqual(handleChangeSpy.callCount, 1);
assert.ok(handleChangeSpy.calledWith('2710'));
assert.strictEqual(
wrapper.find('.currency-display-component').text(),
expect(handleChangeSpy.callCount).toStrictEqual(1);
expect(handleChangeSpy.calledWith('2710')).toStrictEqual(true);
expect(wrapper.find('.currency-display-component').text()).toStrictEqual(
'$462.12USD',
);
assert.strictEqual(tokenInputInstance.state.decimalValue, 1);
assert.strictEqual(tokenInputInstance.state.hexValue, '2710');
expect(tokenInputInstance.state.decimalValue).toStrictEqual(1);
expect(tokenInputInstance.state.hexValue).toStrictEqual('2710');
});
it('should change the state and pass in a new decimalValue when props.value changes', function () {
it('should change the state and pass in a new decimalValue when props.value changes', () => {
const mockStore = {
metamask: {
currentCurrency: 'usd',
@ -332,17 +328,19 @@ describe('TokenInput Component', function () {
</Provider>,
);
assert.ok(wrapper);
expect(wrapper).toHaveLength(1);
const tokenInputInstance = wrapper.find(TokenInput).dive();
assert.strictEqual(tokenInputInstance.state('decimalValue'), 0);
assert.strictEqual(tokenInputInstance.state('hexValue'), undefined);
assert.strictEqual(tokenInputInstance.find(UnitInput).props().value, 0);
expect(tokenInputInstance.state('decimalValue')).toStrictEqual(0);
expect(tokenInputInstance.state('hexValue')).toBeUndefined();
expect(tokenInputInstance.find(UnitInput).props().value).toStrictEqual(0);
tokenInputInstance.setProps({ value: '2710' });
tokenInputInstance.update();
assert.strictEqual(tokenInputInstance.state('decimalValue'), '1');
assert.strictEqual(tokenInputInstance.state('hexValue'), '2710');
assert.strictEqual(tokenInputInstance.find(UnitInput).props().value, '1');
expect(tokenInputInstance.state('decimalValue')).toStrictEqual('1');
expect(tokenInputInstance.state('hexValue')).toStrictEqual('2710');
expect(tokenInputInstance.find(UnitInput).props().value).toStrictEqual(
'1',
);
});
});
});

View File

@ -1,99 +1,98 @@
import assert from 'assert';
import React from 'react';
import { shallow, mount } from 'enzyme';
import sinon from 'sinon';
import UnitInput from './unit-input.component';
describe('UnitInput Component', function () {
describe('rendering', function () {
it('should render properly without a suffix', function () {
describe('UnitInput Component', () => {
describe('rendering', () => {
it('should render properly without a suffix', () => {
const wrapper = shallow(<UnitInput />);
assert.ok(wrapper);
assert.strictEqual(wrapper.find('.unit-input__suffix').length, 0);
expect(wrapper).toHaveLength(1);
expect(wrapper.find('.unit-input__suffix')).toHaveLength(0);
});
it('should render properly with a suffix', function () {
it('should render properly with a suffix', () => {
const wrapper = shallow(<UnitInput suffix="ETH" />);
assert.ok(wrapper);
assert.strictEqual(wrapper.find('.unit-input__suffix').length, 1);
assert.strictEqual(wrapper.find('.unit-input__suffix').text(), 'ETH');
expect(wrapper).toHaveLength(1);
expect(wrapper.find('.unit-input__suffix')).toHaveLength(1);
expect(wrapper.find('.unit-input__suffix').text()).toStrictEqual('ETH');
});
it('should render properly with a child component', function () {
it('should render properly with a child component', () => {
const wrapper = shallow(
<UnitInput>
<div className="testing">TESTCOMPONENT</div>
</UnitInput>,
);
assert.ok(wrapper);
assert.strictEqual(wrapper.find('.testing').length, 1);
assert.strictEqual(wrapper.find('.testing').text(), 'TESTCOMPONENT');
expect(wrapper).toHaveLength(1);
expect(wrapper.find('.testing')).toHaveLength(1);
expect(wrapper.find('.testing').text()).toStrictEqual('TESTCOMPONENT');
});
it('should render with an error class when props.error === true', function () {
it('should render with an error class when props.error === true', () => {
const wrapper = shallow(<UnitInput error />);
assert.ok(wrapper);
assert.strictEqual(wrapper.find('.unit-input--error').length, 1);
expect(wrapper).toHaveLength(1);
expect(wrapper.find('.unit-input--error')).toHaveLength(1);
});
});
describe('handling actions', function () {
describe('handling actions', () => {
const handleChangeSpy = sinon.spy();
const handleBlurSpy = sinon.spy();
afterEach(function () {
afterEach(() => {
handleChangeSpy.resetHistory();
handleBlurSpy.resetHistory();
});
it('should focus the input on component click', function () {
it('should focus the input on component click', () => {
const wrapper = mount(<UnitInput />);
assert.ok(wrapper);
expect(wrapper).toHaveLength(1);
const handleFocusSpy = sinon.spy(wrapper.instance(), 'handleFocus');
wrapper.instance().forceUpdate();
wrapper.update();
assert.strictEqual(handleFocusSpy.callCount, 0);
expect(handleFocusSpy.callCount).toStrictEqual(0);
wrapper.find('.unit-input').simulate('click');
assert.strictEqual(handleFocusSpy.callCount, 1);
expect(handleFocusSpy.callCount).toStrictEqual(1);
});
it('should call onChange on input changes with the value', function () {
it('should call onChange on input changes with the value', () => {
const wrapper = mount(<UnitInput onChange={handleChangeSpy} />);
assert.ok(wrapper);
assert.strictEqual(handleChangeSpy.callCount, 0);
expect(wrapper).toHaveLength(1);
expect(handleChangeSpy.callCount).toStrictEqual(0);
const input = wrapper.find('input');
input.simulate('change', { target: { value: 123 } });
assert.strictEqual(handleChangeSpy.callCount, 1);
assert.ok(handleChangeSpy.calledWith(123));
assert.strictEqual(wrapper.state('value'), 123);
expect(handleChangeSpy.callCount).toStrictEqual(1);
expect(handleChangeSpy.calledWith(123)).toStrictEqual(true);
expect(wrapper.state('value')).toStrictEqual(123);
});
it('should set the component state value with props.value', function () {
it('should set the component state value with props.value', () => {
const wrapper = mount(<UnitInput value={123} />);
assert.ok(wrapper);
assert.strictEqual(wrapper.state('value'), 123);
expect(wrapper).toHaveLength(1);
expect(wrapper.state('value')).toStrictEqual(123);
});
it('should update the component state value with props.value', function () {
it('should update the component state value with props.value', () => {
const wrapper = mount(<UnitInput onChange={handleChangeSpy} />);
assert.ok(wrapper);
assert.strictEqual(handleChangeSpy.callCount, 0);
expect(wrapper).toHaveLength(1);
expect(handleChangeSpy.callCount).toStrictEqual(0);
const input = wrapper.find('input');
input.simulate('change', { target: { value: 123 } });
assert.strictEqual(wrapper.state('value'), 123);
assert.strictEqual(handleChangeSpy.callCount, 1);
assert.ok(handleChangeSpy.calledWith(123));
expect(wrapper.state('value')).toStrictEqual(123);
expect(handleChangeSpy.callCount).toStrictEqual(1);
expect(handleChangeSpy.calledWith(123)).toStrictEqual(true);
wrapper.setProps({ value: 456 });
assert.strictEqual(wrapper.state('value'), 456);
assert.strictEqual(handleChangeSpy.callCount, 1);
expect(wrapper.state('value')).toStrictEqual(456);
expect(handleChangeSpy.callCount).toStrictEqual(1);
});
});
});

View File

@ -1,10 +1,9 @@
import assert from 'assert';
import * as actionConstants from '../../store/actionConstants';
import reduceApp from './app';
const actions = actionConstants;
describe('App State', function () {
describe('App State', () => {
const metamaskState = {
selectedAddress: '0xAddress',
identities: {
@ -15,31 +14,31 @@ describe('App State', function () {
},
};
it('App init state', function () {
it('app init state', () => {
const initState = reduceApp(metamaskState, {});
assert(initState);
expect.anything(initState);
});
it('sets networkDropdownOpen dropdown to true', function () {
it('sets networkDropdownOpen dropdown to true', () => {
const state = reduceApp(metamaskState, {
type: actions.NETWORK_DROPDOWN_OPEN,
});
assert.equal(state.networkDropdownOpen, true);
expect(state.networkDropdownOpen).toStrictEqual(true);
});
it('sets networkDropdownOpen dropdown to false', function () {
it('sets networkDropdownOpen dropdown to false', () => {
const dropdown = { networkDropdowopen: true };
const state = { ...metamaskState, ...dropdown };
const newState = reduceApp(state, {
type: actions.NETWORK_DROPDOWN_CLOSE,
});
assert.equal(newState.networkDropdownOpen, false);
expect(newState.networkDropdownOpen).toStrictEqual(false);
});
it('opens sidebar', function () {
it('opens sidebar', () => {
const value = {
transitionName: 'sidebar-right',
type: 'wallet-view',
@ -50,10 +49,10 @@ describe('App State', function () {
value,
});
assert.deepEqual(state.sidebar, value);
expect(state.sidebar).toStrictEqual(value);
});
it('closes sidebar', function () {
it('closes sidebar', () => {
const openSidebar = { sidebar: { isOpen: true } };
const state = { ...metamaskState, ...openSidebar };
@ -61,40 +60,40 @@ describe('App State', function () {
type: actions.SIDEBAR_CLOSE,
});
assert.equal(newState.sidebar.isOpen, false);
expect(newState.sidebar.isOpen).toStrictEqual(false);
});
it('opens alert', function () {
it('opens alert', () => {
const state = reduceApp(metamaskState, {
type: actions.ALERT_OPEN,
value: 'test message',
});
assert.equal(state.alertOpen, true);
assert.equal(state.alertMessage, 'test message');
expect(state.alertOpen).toStrictEqual(true);
expect(state.alertMessage).toStrictEqual('test message');
});
it('closes alert', function () {
it('closes alert', () => {
const alert = { alertOpen: true, alertMessage: 'test message' };
const state = { ...metamaskState, ...alert };
const newState = reduceApp(state, {
type: actions.ALERT_CLOSE,
});
assert.equal(newState.alertOpen, false);
assert.equal(newState.alertMessage, null);
expect(newState.alertOpen).toStrictEqual(false);
expect(newState.alertMessage).toBeNull();
});
it('detects qr code data', function () {
it('detects qr code data', () => {
const state = reduceApp(metamaskState, {
type: actions.QR_CODE_DETECTED,
value: 'qr data',
});
assert.equal(state.qrCodeData, 'qr data');
expect(state.qrCodeData).toStrictEqual('qr data');
});
it('opens modal', function () {
it('opens modal', () => {
const state = reduceApp(metamaskState, {
type: actions.MODAL_OPEN,
payload: {
@ -102,11 +101,11 @@ describe('App State', function () {
},
});
assert.equal(state.modal.open, true);
assert.equal(state.modal.modalState.name, 'test');
expect(state.modal.open).toStrictEqual(true);
expect(state.modal.modalState.name).toStrictEqual('test');
});
it('closes modal, but moves open modal state to previous modal state', function () {
it('closes modal, but moves open modal state to previous modal state', () => {
const opensModal = {
modal: {
open: true,
@ -121,49 +120,49 @@ describe('App State', function () {
type: actions.MODAL_CLOSE,
});
assert.equal(newState.modal.open, false);
assert.equal(newState.modal.modalState.name, null);
expect(newState.modal.open).toStrictEqual(false);
expect(newState.modal.modalState.name).toBeNull();
});
it('shows send token page', function () {
it('shows send token page', () => {
const state = reduceApp(metamaskState, {
type: actions.SHOW_SEND_TOKEN_PAGE,
});
assert.equal(state.warning, null);
expect(state.warning).toBeNull();
});
it('locks Metamask', function () {
it('locks Metamask', () => {
const state = reduceApp(metamaskState, {
type: actions.LOCK_METAMASK,
});
assert.equal(state.warning, null);
expect(state.warning).toBeNull();
});
it('goes home', function () {
it('goes home', () => {
const state = reduceApp(metamaskState, {
type: actions.GO_HOME,
});
assert.equal(state.accountDetail.subview, 'transactions');
assert.equal(state.accountDetail.accountExport, 'none');
assert.equal(state.accountDetail.privateKey, '');
assert.equal(state.warning, null);
expect(state.accountDetail.subview).toStrictEqual('transactions');
expect(state.accountDetail.accountExport).toStrictEqual('none');
expect(state.accountDetail.privateKey).toStrictEqual('');
expect(state.warning).toBeNull();
});
it('shows account detail', function () {
it('shows account detail', () => {
const state = reduceApp(metamaskState, {
type: actions.SHOW_ACCOUNT_DETAIL,
value: 'context address',
});
assert.equal(state.forgottenPassword, null); // default
assert.equal(state.accountDetail.subview, 'transactions'); // default
assert.equal(state.accountDetail.accountExport, 'none'); // default
assert.equal(state.accountDetail.privateKey, ''); // default
expect(state.forgottenPassword).toBeNull(); // default
expect(state.accountDetail.subview).toStrictEqual('transactions'); // default
expect(state.accountDetail.accountExport).toStrictEqual('none'); // default
expect(state.accountDetail.privateKey).toStrictEqual(''); // default
});
it('clears account details', function () {
it('clears account details', () => {
const exportPrivKeyModal = {
accountDetail: {
subview: 'export',
@ -177,21 +176,21 @@ describe('App State', function () {
type: actions.CLEAR_ACCOUNT_DETAILS,
});
assert.deepStrictEqual(newState.accountDetail, {});
expect(newState.accountDetail).toStrictEqual({});
});
it('shoes account page', function () {
it('shoes account page', () => {
const state = reduceApp(metamaskState, {
type: actions.SHOW_ACCOUNTS_PAGE,
});
assert.equal(state.isLoading, false);
assert.equal(state.warning, null);
assert.equal(state.scrollToBottom, false);
assert.equal(state.forgottenPassword, false);
expect(state.isLoading).toStrictEqual(false);
expect(state.warning).toBeNull();
expect(state.scrollToBottom).toStrictEqual(false);
expect(state.forgottenPassword).toStrictEqual(false);
});
it('shows confirm tx page', function () {
it('shows confirm tx page', () => {
const txs = {
unapprovedTxs: {
1: {
@ -208,12 +207,12 @@ describe('App State', function () {
id: 2,
});
assert.equal(state.txId, 2);
assert.equal(state.warning, null);
assert.equal(state.isLoading, false);
expect(state.txId).toStrictEqual(2);
expect(state.warning).toBeNull();
expect(state.isLoading).toStrictEqual(false);
});
it('completes tx continues to show pending txs current view context', function () {
it('completes tx continues to show pending txs current view context', () => {
const txs = {
unapprovedTxs: {
1: {
@ -234,11 +233,11 @@ describe('App State', function () {
},
});
assert.equal(state.txId, null);
assert.equal(state.warning, null);
expect(state.txId).toBeNull();
expect(state.warning).toBeNull();
});
it('returns to account detail page when no unconf actions completed tx', function () {
it('returns to account detail page when no unconf actions completed tx', () => {
const state = reduceApp(metamaskState, {
type: actions.COMPLETED_TX,
value: {
@ -246,38 +245,38 @@ describe('App State', function () {
},
});
assert.equal(state.warning, null);
assert.equal(state.accountDetail.subview, 'transactions');
expect(state.warning).toBeNull();
expect(state.accountDetail.subview).toStrictEqual('transactions');
});
it('sets default warning when unlock fails', function () {
it('sets default warning when unlock fails', () => {
const state = reduceApp(metamaskState, {
type: actions.UNLOCK_FAILED,
});
assert.equal(state.warning, 'Incorrect password. Try again.');
expect(state.warning).toStrictEqual('Incorrect password. Try again.');
});
it('sets errors when unlock fails', function () {
it('sets errors when unlock fails', () => {
const state = reduceApp(metamaskState, {
type: actions.UNLOCK_FAILED,
value: 'errors',
});
assert.equal(state.warning, 'errors');
expect(state.warning).toStrictEqual('errors');
});
it('sets warning to empty string when unlock succeeds', function () {
it('sets warning to empty string when unlock succeeds', () => {
const errorState = { warning: 'errors' };
const oldState = { ...metamaskState, ...errorState };
const state = reduceApp(oldState, {
type: actions.UNLOCK_SUCCEEDED,
});
assert.equal(state.warning, '');
expect(state.warning).toStrictEqual('');
});
it('sets hardware wallet default hd path', function () {
it('sets hardware wallet default hd path', () => {
const hdPaths = {
trezor: "m/44'/60'/0'/0",
ledger: "m/44'/60'/0'",
@ -290,20 +289,20 @@ describe('App State', function () {
},
});
assert.deepEqual(state.defaultHdPaths, hdPaths);
expect(state.defaultHdPaths).toStrictEqual(hdPaths);
});
it('shows loading message', function () {
it('shows loading message', () => {
const state = reduceApp(metamaskState, {
type: actions.SHOW_LOADING,
value: 'loading',
});
assert.equal(state.isLoading, true);
assert.equal(state.loadingMessage, 'loading');
expect(state.isLoading).toStrictEqual(true);
expect(state.loadingMessage).toStrictEqual('loading');
});
it('hides loading message', function () {
it('hides loading message', () => {
const loadingState = { isLoading: true };
const oldState = { ...metamaskState, ...loadingState };
@ -311,64 +310,64 @@ describe('App State', function () {
type: actions.HIDE_LOADING,
});
assert.equal(state.isLoading, false);
expect(state.isLoading).toStrictEqual(false);
});
it('displays warning', function () {
it('displays warning', () => {
const state = reduceApp(metamaskState, {
type: actions.DISPLAY_WARNING,
value: 'warning',
});
assert.equal(state.isLoading, false);
assert.equal(state.warning, 'warning');
expect(state.isLoading).toStrictEqual(false);
expect(state.warning).toStrictEqual('warning');
});
it('hides warning', function () {
it('hides warning', () => {
const displayWarningState = { warning: 'warning' };
const oldState = { ...metamaskState, ...displayWarningState };
const state = reduceApp(oldState, {
type: actions.HIDE_WARNING,
});
assert.equal(state.warning, undefined);
expect(state.warning).toBeUndefined();
});
it('shows private key', function () {
it('shows private key', () => {
const state = reduceApp(metamaskState, {
type: actions.SHOW_PRIVATE_KEY,
value: 'private key',
});
assert.equal(state.accountDetail.subview, 'export');
assert.equal(state.accountDetail.accountExport, 'completed');
assert.equal(state.accountDetail.privateKey, 'private key');
expect(state.accountDetail.subview).toStrictEqual('export');
expect(state.accountDetail.accountExport).toStrictEqual('completed');
expect(state.accountDetail.privateKey).toStrictEqual('private key');
});
it('set mouse user state', function () {
it('set mouse user state', () => {
const state = reduceApp(metamaskState, {
type: actions.SET_MOUSE_USER_STATE,
value: true,
});
assert.equal(state.isMouseUser, true);
expect(state.isMouseUser).toStrictEqual(true);
});
it('sets gas loading', function () {
it('sets gas loading', () => {
const state = reduceApp(metamaskState, {
type: actions.GAS_LOADING_STARTED,
});
assert.equal(state.gasIsLoading, true);
expect(state.gasIsLoading).toStrictEqual(true);
});
it('unsets gas loading', function () {
it('unsets gas loading', () => {
const gasLoadingState = { gasIsLoading: true };
const oldState = { ...metamaskState, ...gasLoadingState };
const state = reduceApp(oldState, {
type: actions.GAS_LOADING_FINISHED,
});
assert.equal(state.gasIsLoading, false);
expect(state.gasIsLoading).toStrictEqual(false);
});
});

View File

@ -1,4 +1,3 @@
import assert from 'assert';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import sinon from 'sinon';
@ -37,8 +36,8 @@ const UPDATE_NONCE = 'metamask/confirm-transaction/UPDATE_NONCE';
const CLEAR_CONFIRM_TRANSACTION =
'metamask/confirm-transaction/CLEAR_CONFIRM_TRANSACTION';
describe('Confirm Transaction Duck', function () {
describe('State changes', function () {
describe('Confirm Transaction Duck', () => {
describe('State changes', () => {
const mockState = {
txData: {
id: 1,
@ -58,61 +57,57 @@ describe('Confirm Transaction Duck', function () {
nonce: '0x0',
};
it('should initialize state', function () {
assert.deepStrictEqual(
ConfirmTransactionReducer(undefined, {}),
it('should initialize state', () => {
expect(ConfirmTransactionReducer(undefined, {})).toStrictEqual(
initialState,
);
});
it('should return state unchanged if it does not match a dispatched actions type', function () {
assert.deepStrictEqual(
it('should return state unchanged if it does not match a dispatched actions type', () => {
expect(
ConfirmTransactionReducer(mockState, {
type: 'someOtherAction',
value: 'someValue',
}),
{ ...mockState },
);
).toStrictEqual({ ...mockState });
});
it('should set txData when receiving a UPDATE_TX_DATA action', function () {
assert.deepStrictEqual(
it('should set txData when receiving a UPDATE_TX_DATA action', () => {
expect(
ConfirmTransactionReducer(mockState, {
type: UPDATE_TX_DATA,
payload: {
id: 2,
},
}),
{
...mockState,
txData: {
...mockState.txData,
id: 2,
},
).toStrictEqual({
...mockState,
txData: {
...mockState.txData,
id: 2,
},
);
});
});
it('should set tokenData when receiving a UPDATE_TOKEN_DATA action', function () {
assert.deepStrictEqual(
it('should set tokenData when receiving a UPDATE_TOKEN_DATA action', () => {
expect(
ConfirmTransactionReducer(mockState, {
type: UPDATE_TOKEN_DATA,
payload: {
name: 'defToken',
},
}),
{
...mockState,
tokenData: {
...mockState.tokenData,
name: 'defToken',
},
).toStrictEqual({
...mockState,
tokenData: {
...mockState.tokenData,
name: 'defToken',
},
);
});
});
it('should update transaction amounts when receiving an UPDATE_TRANSACTION_AMOUNTS action', function () {
assert.deepStrictEqual(
it('should update transaction amounts when receiving an UPDATE_TRANSACTION_AMOUNTS action', () => {
expect(
ConfirmTransactionReducer(mockState, {
type: UPDATE_TRANSACTION_AMOUNTS,
payload: {
@ -121,17 +116,16 @@ describe('Confirm Transaction Duck', function () {
hexTransactionAmount: '0x1',
},
}),
{
...mockState,
fiatTransactionAmount: '123.45',
ethTransactionAmount: '.5',
hexTransactionAmount: '0x1',
},
);
).toStrictEqual({
...mockState,
fiatTransactionAmount: '123.45',
ethTransactionAmount: '.5',
hexTransactionAmount: '0x1',
});
});
it('should update transaction fees when receiving an UPDATE_TRANSACTION_FEES action', function () {
assert.deepStrictEqual(
it('should update transaction fees when receiving an UPDATE_TRANSACTION_FEES action', () => {
expect(
ConfirmTransactionReducer(mockState, {
type: UPDATE_TRANSACTION_FEES,
payload: {
@ -140,17 +134,16 @@ describe('Confirm Transaction Duck', function () {
hexTransactionFee: '0x1',
},
}),
{
...mockState,
fiatTransactionFee: '123.45',
ethTransactionFee: '.5',
hexTransactionFee: '0x1',
},
);
).toStrictEqual({
...mockState,
fiatTransactionFee: '123.45',
ethTransactionFee: '.5',
hexTransactionFee: '0x1',
});
});
it('should update transaction totals when receiving an UPDATE_TRANSACTION_TOTALS action', function () {
assert.deepStrictEqual(
it('should update transaction totals when receiving an UPDATE_TRANSACTION_TOTALS action', () => {
expect(
ConfirmTransactionReducer(mockState, {
type: UPDATE_TRANSACTION_TOTALS,
payload: {
@ -159,35 +152,32 @@ describe('Confirm Transaction Duck', function () {
hexTransactionTotal: '0x1',
},
}),
{
...mockState,
fiatTransactionTotal: '123.45',
ethTransactionTotal: '.5',
hexTransactionTotal: '0x1',
},
);
).toStrictEqual({
...mockState,
fiatTransactionTotal: '123.45',
ethTransactionTotal: '.5',
hexTransactionTotal: '0x1',
});
});
it('should update nonce when receiving an UPDATE_NONCE action', function () {
assert.deepStrictEqual(
it('should update nonce when receiving an UPDATE_NONCE action', () => {
expect(
ConfirmTransactionReducer(mockState, {
type: UPDATE_NONCE,
payload: '0x1',
}),
{
...mockState,
nonce: '0x1',
},
);
).toStrictEqual({
...mockState,
nonce: '0x1',
});
});
it('should clear confirmTransaction when receiving a FETCH_DATA_END action', function () {
assert.deepStrictEqual(
it('should clear confirmTransaction when receiving a FETCH_DATA_END action', () => {
expect(
ConfirmTransactionReducer(mockState, {
type: CLEAR_CONFIRM_TRANSACTION,
}),
initialState,
);
).toStrictEqual(initialState);
});
});
@ -199,7 +189,7 @@ describe('Confirm Transaction Duck', function () {
payload: txData,
};
assert.deepStrictEqual(actions.updateTxData(txData), expectedAction);
expect(actions.updateTxData(txData)).toStrictEqual(expectedAction);
});
it('should create an action to update tokenData', function () {
@ -209,10 +199,7 @@ describe('Confirm Transaction Duck', function () {
payload: tokenData,
};
assert.deepStrictEqual(
actions.updateTokenData(tokenData),
expectedAction,
);
expect(actions.updateTokenData(tokenData)).toStrictEqual(expectedAction);
});
it('should create an action to update transaction amounts', function () {
@ -222,10 +209,9 @@ describe('Confirm Transaction Duck', function () {
payload: transactionAmounts,
};
assert.deepStrictEqual(
expect(
actions.updateTransactionAmounts(transactionAmounts),
expectedAction,
);
).toStrictEqual(expectedAction);
});
it('should create an action to update transaction fees', function () {
@ -235,8 +221,7 @@ describe('Confirm Transaction Duck', function () {
payload: transactionFees,
};
assert.deepStrictEqual(
actions.updateTransactionFees(transactionFees),
expect(actions.updateTransactionFees(transactionFees)).toStrictEqual(
expectedAction,
);
});
@ -248,8 +233,7 @@ describe('Confirm Transaction Duck', function () {
payload: transactionTotals,
};
assert.deepStrictEqual(
actions.updateTransactionTotals(transactionTotals),
expect(actions.updateTransactionTotals(transactionTotals)).toStrictEqual(
expectedAction,
);
});
@ -261,20 +245,20 @@ describe('Confirm Transaction Duck', function () {
payload: nonce,
};
assert.deepStrictEqual(actions.updateNonce(nonce), expectedAction);
expect(actions.updateNonce(nonce)).toStrictEqual(expectedAction);
});
it('should create an action to clear confirmTransaction', function () {
it('should create an action to clear confirmTransaction', () => {
const expectedAction = {
type: CLEAR_CONFIRM_TRANSACTION,
};
assert.deepStrictEqual(actions.clearConfirmTransaction(), expectedAction);
expect(actions.clearConfirmTransaction()).toStrictEqual(expectedAction);
});
});
describe('Thunk actions', function () {
beforeEach(function () {
describe('Thunk actions', () => {
beforeEach(() => {
global.eth = {
getCode: sinon
.stub()
@ -288,7 +272,7 @@ describe('Confirm Transaction Duck', function () {
global.eth.getCode.resetHistory();
});
it('updates txData and updates gas values in confirmTransaction', function () {
it('updates txData and updates gas values in confirmTransaction', () => {
const txData = {
history: [],
id: 2603411941761054,
@ -348,13 +332,13 @@ describe('Confirm Transaction Duck', function () {
store.dispatch(actions.updateTxDataAndCalculate(txData));
const storeActions = store.getActions();
assert.strictEqual(storeActions.length, expectedActions.length);
expect(storeActions).toHaveLength(expectedActions.length);
storeActions.forEach((action, index) =>
assert.strictEqual(action.type, expectedActions[index]),
expect(action.type).toStrictEqual(expectedActions[index]),
);
});
it('updates confirmTransaction transaction', function () {
it('updates confirmTransaction transaction', () => {
const mockState = {
metamask: {
conversionRate: 468.58,
@ -397,10 +381,10 @@ describe('Confirm Transaction Duck', function () {
store.dispatch(actions.setTransactionToConfirm(2603411941761054));
const storeActions = store.getActions();
assert.strictEqual(storeActions.length, expectedActions.length);
expect(storeActions).toHaveLength(expectedActions.length);
storeActions.forEach((action, index) =>
assert.strictEqual(action.type, expectedActions[index]),
expect(action.type).toStrictEqual(expectedActions[index]),
);
});
});

View File

@ -1,9 +1,8 @@
import assert from 'assert';
import nock from 'nock';
import sinon from 'sinon';
import BN from 'bn.js';
import GasDuck, {
import GasReducer, {
basicGasEstimatesLoadingStarted,
basicGasEstimatesLoadingFinished,
setBasicGasEstimateData,
@ -12,15 +11,31 @@ import GasDuck, {
fetchBasicGasEstimates,
} from './gas.duck';
const mockGasPriceApiResponse = {
SafeGasPrice: 10,
ProposeGasPrice: 20,
FastGasPrice: 30,
};
jest.mock('../../../lib/storage-helpers.js', () => ({
getStorageItem: jest.fn(),
setStorageItem: jest.fn(),
}));
const GasReducer = GasDuck;
describe('Gas Duck', () => {
let tempDateNow;
const mockGasPriceApiResponse = {
SafeGasPrice: 10,
ProposeGasPrice: 20,
FastGasPrice: 30,
};
beforeEach(() => {
tempDateNow = global.Date.now;
global.Date.now = () => 2000000;
});
afterEach(() => {
sinon.restore();
global.Date.now = tempDateNow;
});
describe('Gas Duck', function () {
const mockState = {
mockProp: 123,
};
@ -55,84 +70,81 @@ describe('Gas Duck', function () {
const SET_CUSTOM_GAS_LIMIT = 'metamask/gas/SET_CUSTOM_GAS_LIMIT';
const SET_CUSTOM_GAS_PRICE = 'metamask/gas/SET_CUSTOM_GAS_PRICE';
describe('GasReducer()', function () {
it('should initialize state', function () {
assert.deepStrictEqual(GasReducer(undefined, {}), initState);
describe('GasReducer()', () => {
it('should initialize state', () => {
expect(GasReducer(undefined, {})).toStrictEqual(initState);
});
it('should return state unchanged if it does not match a dispatched actions type', function () {
assert.deepStrictEqual(
it('should return state unchanged if it does not match a dispatched actions type', () => {
expect(
GasReducer(mockState, {
type: 'someOtherAction',
value: 'someValue',
}),
mockState,
);
).toStrictEqual(mockState);
});
it('should set basicEstimateIsLoading to true when receiving a BASIC_GAS_ESTIMATE_LOADING_STARTED action', function () {
assert.deepStrictEqual(
it('should set basicEstimateIsLoading to true when receiving a BASIC_GAS_ESTIMATE_LOADING_STARTED action', () => {
expect(
GasReducer(mockState, { type: BASIC_GAS_ESTIMATE_LOADING_STARTED }),
{ basicEstimateIsLoading: true, ...mockState },
);
).toStrictEqual({ basicEstimateIsLoading: true, ...mockState });
});
it('should set basicEstimateIsLoading to false when receiving a BASIC_GAS_ESTIMATE_LOADING_FINISHED action', function () {
assert.deepStrictEqual(
it('should set basicEstimateIsLoading to false when receiving a BASIC_GAS_ESTIMATE_LOADING_FINISHED action', () => {
expect(
GasReducer(mockState, { type: BASIC_GAS_ESTIMATE_LOADING_FINISHED }),
{ basicEstimateIsLoading: false, ...mockState },
);
).toStrictEqual({ basicEstimateIsLoading: false, ...mockState });
});
it('should set basicEstimates when receiving a SET_BASIC_GAS_ESTIMATE_DATA action', function () {
assert.deepStrictEqual(
it('should set basicEstimates when receiving a SET_BASIC_GAS_ESTIMATE_DATA action', () => {
expect(
GasReducer(mockState, {
type: SET_BASIC_GAS_ESTIMATE_DATA,
value: { someProp: 'someData123' },
}),
{ basicEstimates: { someProp: 'someData123' }, ...mockState },
);
).toStrictEqual({
basicEstimates: { someProp: 'someData123' },
...mockState,
});
});
it('should set customData.price when receiving a SET_CUSTOM_GAS_PRICE action', function () {
assert.deepStrictEqual(
it('should set customData.price when receiving a SET_CUSTOM_GAS_PRICE action', () => {
expect(
GasReducer(mockState, {
type: SET_CUSTOM_GAS_PRICE,
value: 4321,
}),
{ customData: { price: 4321 }, ...mockState },
);
).toStrictEqual({ customData: { price: 4321 }, ...mockState });
});
it('should set customData.limit when receiving a SET_CUSTOM_GAS_LIMIT action', function () {
assert.deepStrictEqual(
it('should set customData.limit when receiving a SET_CUSTOM_GAS_LIMIT action', () => {
expect(
GasReducer(mockState, {
type: SET_CUSTOM_GAS_LIMIT,
value: 9876,
}),
{ customData: { limit: 9876 }, ...mockState },
);
).toStrictEqual({ customData: { limit: 9876 }, ...mockState });
});
});
describe('basicGasEstimatesLoadingStarted', function () {
it('should create the correct action', function () {
assert.deepStrictEqual(basicGasEstimatesLoadingStarted(), {
describe('basicGasEstimatesLoadingStarted', () => {
it('should create the correct action', () => {
expect(basicGasEstimatesLoadingStarted()).toStrictEqual({
type: BASIC_GAS_ESTIMATE_LOADING_STARTED,
});
});
});
describe('basicGasEstimatesLoadingFinished', function () {
it('should create the correct action', function () {
assert.deepStrictEqual(basicGasEstimatesLoadingFinished(), {
describe('basicGasEstimatesLoadingFinished', () => {
it('should create the correct action', () => {
expect(basicGasEstimatesLoadingFinished()).toStrictEqual({
type: BASIC_GAS_ESTIMATE_LOADING_FINISHED,
});
});
});
describe('fetchBasicGasEstimates', function () {
it('should call fetch with the expected params', async function () {
describe('fetchBasicGasEstimates', () => {
it('should call fetch with the expected params', async () => {
const mockDistpatch = sinon.spy();
const windowFetchSpy = sinon.spy(window, 'fetch');
@ -144,23 +156,23 @@ describe('Gas Duck', function () {
gas: { ...initState },
metamask: { provider: { ...providerState } },
}));
assert.deepStrictEqual(mockDistpatch.getCall(0).args, [
expect(mockDistpatch.getCall(0).args).toStrictEqual([
{ type: BASIC_GAS_ESTIMATE_LOADING_STARTED },
]);
assert.ok(
expect(
windowFetchSpy
.getCall(0)
.args[0].startsWith('https://api.metaswap.codefi.network/gasPrices'),
'should fetch metaswap /gasPrices',
);
).toStrictEqual(true);
assert.deepStrictEqual(mockDistpatch.getCall(2).args, [
expect(mockDistpatch.getCall(2).args).toStrictEqual([
{ type: BASIC_GAS_ESTIMATE_LOADING_FINISHED },
]);
});
it('should call fetch with the expected params for test network', async function () {
it('should call fetch with the expected params for test network', async () => {
global.eth = { gasPrice: sinon.fake.returns(new BN(48199313, 10)) };
const mockDistpatch = sinon.spy();
@ -174,13 +186,13 @@ describe('Gas Duck', function () {
};
await fetchBasicGasEstimates()(mockDistpatch, () => ({
gas: { ...initState },
gas: { ...initState, basicPriceAEstimatesLastRetrieved: 1000000 },
metamask: { provider: { ...providerStateForTestNetwork } },
}));
assert.deepStrictEqual(mockDistpatch.getCall(0).args, [
expect(mockDistpatch.getCall(0).args).toStrictEqual([
{ type: BASIC_GAS_ESTIMATE_LOADING_STARTED },
]);
assert.deepStrictEqual(mockDistpatch.getCall(1).args, [
expect(mockDistpatch.getCall(1).args).toStrictEqual([
{
type: SET_BASIC_GAS_ESTIMATE_DATA,
value: {
@ -188,33 +200,33 @@ describe('Gas Duck', function () {
},
},
]);
assert.deepStrictEqual(mockDistpatch.getCall(2).args, [
expect(mockDistpatch.getCall(2).args).toStrictEqual([
{ type: BASIC_GAS_ESTIMATE_LOADING_FINISHED },
]);
});
});
describe('setBasicGasEstimateData', function () {
it('should create the correct action', function () {
assert.deepStrictEqual(setBasicGasEstimateData('mockBasicEstimatData'), {
describe('setBasicGasEstimateData', () => {
it('should create the correct action', () => {
expect(setBasicGasEstimateData('mockBasicEstimatData')).toStrictEqual({
type: SET_BASIC_GAS_ESTIMATE_DATA,
value: 'mockBasicEstimatData',
});
});
});
describe('setCustomGasPrice', function () {
it('should create the correct action', function () {
assert.deepStrictEqual(setCustomGasPrice('mockCustomGasPrice'), {
describe('setCustomGasPrice', () => {
it('should create the correct action', () => {
expect(setCustomGasPrice('mockCustomGasPrice')).toStrictEqual({
type: SET_CUSTOM_GAS_PRICE,
value: 'mockCustomGasPrice',
});
});
});
describe('setCustomGasLimit', function () {
it('should create the correct action', function () {
assert.deepStrictEqual(setCustomGasLimit('mockCustomGasLimit'), {
describe('setCustomGasLimit', () => {
it('should create the correct action', () => {
expect(setCustomGasLimit('mockCustomGasLimit')).toStrictEqual({
type: SET_CUSTOM_GAS_LIMIT,
value: 'mockCustomGasLimit',
});

View File

@ -1,14 +1,13 @@
import assert from 'assert';
import * as actionConstants from '../../store/actionConstants';
import reduceMetamask from './metamask';
describe('MetaMask Reducers', function () {
it('init state', function () {
describe('MetaMask Reducers', () => {
it('init state', () => {
const initState = reduceMetamask(undefined, {});
assert(initState);
expect.anything(initState);
});
it('locks MetaMask', function () {
it('locks MetaMask', () => {
const unlockMetaMaskState = {
isUnlocked: true,
selectedAddress: 'test address',
@ -17,10 +16,10 @@ describe('MetaMask Reducers', function () {
type: actionConstants.LOCK_METAMASK,
});
assert.equal(lockMetaMask.isUnlocked, false);
expect(lockMetaMask.isUnlocked).toStrictEqual(false);
});
it('sets rpc target', function () {
it('sets rpc target', () => {
const state = reduceMetamask(
{},
{
@ -29,10 +28,10 @@ describe('MetaMask Reducers', function () {
},
);
assert.equal(state.provider.rpcUrl, 'https://custom.rpc');
expect(state.provider.rpcUrl).toStrictEqual('https://custom.rpc');
});
it('sets provider type', function () {
it('sets provider type', () => {
const state = reduceMetamask(
{},
{
@ -41,10 +40,10 @@ describe('MetaMask Reducers', function () {
},
);
assert.equal(state.provider.type, 'provider type');
expect(state.provider.type).toStrictEqual('provider type');
});
it('shows account detail', function () {
it('shows account detail', () => {
const state = reduceMetamask(
{},
{
@ -53,12 +52,12 @@ describe('MetaMask Reducers', function () {
},
);
assert.equal(state.isUnlocked, true);
assert.equal(state.isInitialized, true);
assert.equal(state.selectedAddress, 'test address');
expect(state.isUnlocked).toStrictEqual(true);
expect(state.isInitialized).toStrictEqual(true);
expect(state.selectedAddress).toStrictEqual('test address');
});
it('sets account label', function () {
it('sets account label', () => {
const state = reduceMetamask(
{},
{
@ -70,12 +69,12 @@ describe('MetaMask Reducers', function () {
},
);
assert.deepEqual(state.identities, {
expect(state.identities).toStrictEqual({
'test account': { name: 'test label' },
});
});
it('sets current fiat', function () {
it('sets current fiat', () => {
const value = {
currentCurrency: 'yen',
conversionRate: 3.14,
@ -90,12 +89,12 @@ describe('MetaMask Reducers', function () {
},
);
assert.equal(state.currentCurrency, value.currentCurrency);
assert.equal(state.conversionRate, value.conversionRate);
assert.equal(state.conversionDate, value.conversionDate);
expect(state.currentCurrency).toStrictEqual(value.currentCurrency);
expect(state.conversionRate).toStrictEqual(value.conversionRate);
expect(state.conversionDate).toStrictEqual(value.conversionDate);
});
it('updates tokens', function () {
it('updates tokens', () => {
const newTokens = {
address: '0x617b3f8050a0bd94b6b1da02b4384ee5b4df13f4',
decimals: 18,
@ -110,10 +109,10 @@ describe('MetaMask Reducers', function () {
},
);
assert.deepEqual(state.tokens, newTokens);
expect(state.tokens).toStrictEqual(newTokens);
});
it('updates send gas limit', function () {
it('updates send gas limit', () => {
const state = reduceMetamask(
{},
{
@ -122,10 +121,10 @@ describe('MetaMask Reducers', function () {
},
);
assert.equal(state.send.gasLimit, '0xGasLimit');
expect(state.send.gasLimit).toStrictEqual('0xGasLimit');
});
it('updates send gas price', function () {
it('updates send gas price', () => {
const state = reduceMetamask(
{},
{
@ -134,10 +133,10 @@ describe('MetaMask Reducers', function () {
},
);
assert.equal(state.send.gasPrice, '0xGasPrice');
expect(state.send.gasPrice).toStrictEqual('0xGasPrice');
});
it('toggles account menu ', function () {
it('toggles account menu', () => {
const state = reduceMetamask(
{},
{
@ -145,10 +144,10 @@ describe('MetaMask Reducers', function () {
},
);
assert.equal(state.isAccountMenuOpen, true);
expect(state.isAccountMenuOpen).toStrictEqual(true);
});
it('updates gas total', function () {
it('updates gas total', () => {
const state = reduceMetamask(
{},
{
@ -157,10 +156,10 @@ describe('MetaMask Reducers', function () {
},
);
assert.equal(state.send.gasTotal, '0xGasTotal');
expect(state.send.gasTotal).toStrictEqual('0xGasTotal');
});
it('updates send token balance', function () {
it('updates send token balance', () => {
const state = reduceMetamask(
{},
{
@ -169,10 +168,10 @@ describe('MetaMask Reducers', function () {
},
);
assert.equal(state.send.tokenBalance, '0xTokenBalance');
expect(state.send.tokenBalance).toStrictEqual('0xTokenBalance');
});
it('updates data', function () {
it('updates data', () => {
const state = reduceMetamask(
{},
{
@ -181,10 +180,10 @@ describe('MetaMask Reducers', function () {
},
);
assert.equal(state.send.data, '0xData');
expect(state.send.data).toStrictEqual('0xData');
});
it('updates send to', function () {
it('updates send to', () => {
const state = reduceMetamask(
{},
{
@ -196,11 +195,11 @@ describe('MetaMask Reducers', function () {
},
);
assert.equal(state.send.to, '0xAddress');
assert.equal(state.send.toNickname, 'nickname');
expect(state.send.to).toStrictEqual('0xAddress');
expect(state.send.toNickname).toStrictEqual('nickname');
});
it('update send amount', function () {
it('update send amount', () => {
const state = reduceMetamask(
{},
{
@ -209,10 +208,10 @@ describe('MetaMask Reducers', function () {
},
);
assert.equal(state.send.amount, '0xAmount');
expect(state.send.amount).toStrictEqual('0xAmount');
});
it('updates max mode', function () {
it('updates max mode', () => {
const state = reduceMetamask(
{},
{
@ -221,10 +220,10 @@ describe('MetaMask Reducers', function () {
},
);
assert.equal(state.send.maxModeOn, true);
expect(state.send.maxModeOn).toStrictEqual(true);
});
it('update send', function () {
it('update send', () => {
const value = {
gasLimit: '0xGasLimit',
gasPrice: '0xGasPrice',
@ -250,10 +249,10 @@ describe('MetaMask Reducers', function () {
},
);
assert.deepEqual(sendState.send, value);
expect(sendState.send).toStrictEqual(value);
});
it('clears send', function () {
it('clears send', () => {
const initStateSend = {
send: {
gasLimit: null,
@ -292,10 +291,10 @@ describe('MetaMask Reducers', function () {
type: actionConstants.CLEAR_SEND,
});
assert.deepEqual(state.send, initStateSend.send);
expect(state.send).toStrictEqual(initStateSend.send);
});
it('updates value of tx by id', function () {
it('updates value of tx by id', () => {
const oldState = {
currentNetworkTxList: [
{
@ -311,10 +310,10 @@ describe('MetaMask Reducers', function () {
value: 'bar',
});
assert.equal(state.currentNetworkTxList[0].txParams, 'bar');
expect(state.currentNetworkTxList[0].txParams).toStrictEqual('bar');
});
it('sets blockies', function () {
it('sets blockies', () => {
const state = reduceMetamask(
{},
{
@ -323,10 +322,10 @@ describe('MetaMask Reducers', function () {
},
);
assert.equal(state.useBlockie, true);
expect(state.useBlockie).toStrictEqual(true);
});
it('updates an arbitrary feature flag', function () {
it('updates an arbitrary feature flag', () => {
const state = reduceMetamask(
{},
{
@ -337,10 +336,10 @@ describe('MetaMask Reducers', function () {
},
);
assert.equal(state.featureFlags.foo, true);
expect(state.featureFlags.foo).toStrictEqual(true);
});
it('close welcome screen', function () {
it('close welcome screen', () => {
const state = reduceMetamask(
{},
{
@ -348,10 +347,10 @@ describe('MetaMask Reducers', function () {
},
);
assert.equal(state.welcomeScreenSeen, true);
expect(state.welcomeScreenSeen).toStrictEqual(true);
});
it('sets current locale', function () {
it('sets current locale', () => {
const state = reduceMetamask(
{},
{
@ -360,10 +359,10 @@ describe('MetaMask Reducers', function () {
},
);
assert.equal(state.currentLocale, 'ge');
expect(state.currentLocale).toStrictEqual('ge');
});
it('sets pending tokens ', function () {
it('sets pending tokens', () => {
const payload = {
address: '0x617b3f8050a0bd94b6b1da02b4384ee5b4df13f4',
decimals: 18,
@ -378,10 +377,10 @@ describe('MetaMask Reducers', function () {
},
);
assert.deepEqual(pendingTokensState.pendingTokens, payload);
expect(pendingTokensState.pendingTokens).toStrictEqual(payload);
});
it('clears pending tokens', function () {
it('clears pending tokens', () => {
const payload = {
address: '0x617b3f8050a0bd94b6b1da02b4384ee5b4df13f4',
decimals: 18,
@ -396,10 +395,10 @@ describe('MetaMask Reducers', function () {
type: actionConstants.CLEAR_PENDING_TOKENS,
});
assert.deepEqual(state.pendingTokens, {});
expect(state.pendingTokens).toStrictEqual({});
});
it('update ensResolution', function () {
it('update ensResolution', () => {
const state = reduceMetamask(
{},
{
@ -408,11 +407,11 @@ describe('MetaMask Reducers', function () {
},
);
assert.deepEqual(state.send.ensResolution, '0x1337');
assert.deepEqual(state.send.ensResolutionError, '');
expect(state.send.ensResolution).toStrictEqual('0x1337');
expect(state.send.ensResolutionError).toStrictEqual('');
});
it('update ensResolutionError', function () {
it('update ensResolutionError', () => {
const state = reduceMetamask(
{},
{
@ -421,7 +420,7 @@ describe('MetaMask Reducers', function () {
},
);
assert.deepEqual(state.send.ensResolutionError, 'ens name not found');
assert.deepEqual(state.send.ensResolution, null);
expect(state.send.ensResolutionError).toStrictEqual('ens name not found');
expect(state.send.ensResolution).toBeNull();
});
});

View File

@ -1,5 +1,3 @@
import assert from 'assert';
import SendReducer, {
openToDropdown,
closeToDropdown,
@ -8,7 +6,7 @@ import SendReducer, {
hideGasButtonGroup,
} from './send.duck';
describe('Send Duck', function () {
describe('Send Duck', () => {
const mockState = {
mockProp: 123,
};
@ -24,112 +22,107 @@ describe('Send Duck', function () {
const SHOW_GAS_BUTTON_GROUP = 'metamask/send/SHOW_GAS_BUTTON_GROUP';
const HIDE_GAS_BUTTON_GROUP = 'metamask/send/HIDE_GAS_BUTTON_GROUP';
describe('SendReducer()', function () {
it('should initialize state', function () {
assert.deepStrictEqual(SendReducer(undefined, {}), initState);
describe('SendReducer()', () => {
it('should initialize state', () => {
expect(SendReducer(undefined, {})).toStrictEqual(initState);
});
it('should return state unchanged if it does not match a dispatched actions type', function () {
assert.deepStrictEqual(
it('should return state unchanged if it does not match a dispatched actions type', () => {
expect(
SendReducer(mockState, {
type: 'someOtherAction',
value: 'someValue',
}),
mockState,
);
).toStrictEqual(mockState);
});
it('should set toDropdownOpen to true when receiving a OPEN_TO_DROPDOWN action', function () {
assert.deepStrictEqual(
it('should set toDropdownOpen to true when receiving a OPEN_TO_DROPDOWN action', () => {
expect(
SendReducer(mockState, {
type: OPEN_TO_DROPDOWN,
}),
{ toDropdownOpen: true, ...mockState },
);
).toStrictEqual({ toDropdownOpen: true, ...mockState });
});
it('should set toDropdownOpen to false when receiving a CLOSE_TO_DROPDOWN action', function () {
assert.deepStrictEqual(
it('should set toDropdownOpen to false when receiving a CLOSE_TO_DROPDOWN action', () => {
expect(
SendReducer(mockState, {
type: CLOSE_TO_DROPDOWN,
}),
{ toDropdownOpen: false, ...mockState },
);
).toStrictEqual({ toDropdownOpen: false, ...mockState });
});
it('should set gasButtonGroupShown to true when receiving a SHOW_GAS_BUTTON_GROUP action', function () {
assert.deepStrictEqual(
it('should set gasButtonGroupShown to true when receiving a SHOW_GAS_BUTTON_GROUP action', () => {
expect(
SendReducer(
{ ...mockState, gasButtonGroupShown: false },
{ type: SHOW_GAS_BUTTON_GROUP },
),
{ gasButtonGroupShown: true, ...mockState },
);
).toStrictEqual({ gasButtonGroupShown: true, ...mockState });
});
it('should set gasButtonGroupShown to false when receiving a HIDE_GAS_BUTTON_GROUP action', function () {
assert.deepStrictEqual(
it('should set gasButtonGroupShown to false when receiving a HIDE_GAS_BUTTON_GROUP action', () => {
expect(
SendReducer(mockState, { type: HIDE_GAS_BUTTON_GROUP }),
{ gasButtonGroupShown: false, ...mockState },
);
).toStrictEqual({ gasButtonGroupShown: false, ...mockState });
});
it('should extend send.errors with the value of a UPDATE_SEND_ERRORS action', function () {
it('should extend send.errors with the value of a UPDATE_SEND_ERRORS action', () => {
const modifiedMockState = {
...mockState,
errors: {
someError: false,
},
};
assert.deepStrictEqual(
expect(
SendReducer(modifiedMockState, {
type: UPDATE_SEND_ERRORS,
value: { someOtherError: true },
}),
{
...modifiedMockState,
errors: {
someError: false,
someOtherError: true,
},
).toStrictEqual({
...modifiedMockState,
errors: {
someError: false,
someOtherError: true,
},
);
});
});
it('should return the initial state in response to a RESET_SEND_STATE action', function () {
assert.deepStrictEqual(
it('should return the initial state in response to a RESET_SEND_STATE action', () => {
expect(
SendReducer(mockState, {
type: RESET_SEND_STATE,
}),
initState,
);
).toStrictEqual(initState);
});
});
describe('openToDropdown', function () {
assert.deepStrictEqual(openToDropdown(), { type: OPEN_TO_DROPDOWN });
});
describe('closeToDropdown', function () {
assert.deepStrictEqual(closeToDropdown(), { type: CLOSE_TO_DROPDOWN });
});
describe('showGasButtonGroup', function () {
assert.deepStrictEqual(showGasButtonGroup(), {
type: SHOW_GAS_BUTTON_GROUP,
describe('Send Duck Actions', () => {
it('calls openToDropdown action', () => {
expect(openToDropdown()).toStrictEqual({ type: OPEN_TO_DROPDOWN });
});
});
describe('hideGasButtonGroup', function () {
assert.deepStrictEqual(hideGasButtonGroup(), {
type: HIDE_GAS_BUTTON_GROUP,
it('calls closeToDropdown action', () => {
expect(closeToDropdown()).toStrictEqual({ type: CLOSE_TO_DROPDOWN });
});
});
describe('updateSendErrors', function () {
assert.deepStrictEqual(updateSendErrors('mockErrorObject'), {
type: UPDATE_SEND_ERRORS,
value: 'mockErrorObject',
it('calls showGasButtonGroup action', () => {
expect(showGasButtonGroup()).toStrictEqual({
type: SHOW_GAS_BUTTON_GROUP,
});
});
it('calls hideGasButtonGroup action', () => {
expect(hideGasButtonGroup()).toStrictEqual({
type: HIDE_GAS_BUTTON_GROUP,
});
});
it('calls updateSendErrors action', () => {
expect(updateSendErrors('mockErrorObject')).toStrictEqual({
type: UPDATE_SEND_ERRORS,
value: 'mockErrorObject',
});
});
});
});

View File

@ -1,4 +1,3 @@
import assert from 'assert';
import configureMockStore from 'redux-mock-store';
import { mount } from 'enzyme';
import React from 'react';
@ -18,21 +17,21 @@ const mockState = {
},
};
describe('withModalProps', function () {
it('should return a component wrapped with modal state props', function () {
describe('withModalProps', () => {
it('should return a component wrapped with modal state props', () => {
const TestComponent = () => <div className="test">Testing</div>;
const WrappedComponent = withModalProps(TestComponent);
const store = configureMockStore()(mockState);
const wrapper = mount(<WrappedComponent store={store} />);
assert.ok(wrapper);
expect(wrapper).toHaveLength(1);
const testComponent = wrapper.find(TestComponent).at(0);
assert.strictEqual(testComponent.length, 1);
assert.strictEqual(testComponent.find('.test').text(), 'Testing');
expect(testComponent).toHaveLength(1);
expect(testComponent.find('.test').text()).toStrictEqual('Testing');
const testComponentProps = testComponent.props();
assert.strictEqual(testComponentProps.prop1, 'prop1');
assert.strictEqual(testComponentProps.prop2, 2);
assert.strictEqual(testComponentProps.prop3, true);
assert.strictEqual(typeof testComponentProps.hideModal, 'function');
expect(testComponentProps.prop1).toStrictEqual('prop1');
expect(testComponentProps.prop2).toStrictEqual(2);
expect(testComponentProps.prop3).toStrictEqual(true);
expect(typeof testComponentProps.hideModal).toStrictEqual('function');
});
});

View File

@ -1,9 +1,8 @@
import assert from 'assert';
import * as utils from './common.util';
describe('Common utils', function () {
describe('camelCaseToCapitalize', function () {
it('should return a capitalized string from a camel-cased string', function () {
describe('Common utils', () => {
describe('camelCaseToCapitalize', () => {
it('should return a capitalized string from a camel-cased string', () => {
const tests = [
{
test: undefined,
@ -20,7 +19,7 @@ describe('Common utils', function () {
];
tests.forEach(({ test, expected }) => {
assert.strictEqual(utils.camelCaseToCapitalize(test), expected);
expect(utils.camelCaseToCapitalize(test)).toStrictEqual(expected);
});
});
});

View File

@ -1,60 +1,57 @@
import assert from 'assert';
import * as utils from './confirm-tx.util';
describe('Confirm Transaction utils', function () {
describe('increaseLastGasPrice', function () {
it('should increase the gasPrice by 10%', function () {
describe('Confirm Transaction utils', () => {
describe('increaseLastGasPrice', () => {
it('should increase the gasPrice by 10%', () => {
const increasedGasPrice = utils.increaseLastGasPrice('0xa');
assert.strictEqual(increasedGasPrice, '0xb');
expect(increasedGasPrice).toStrictEqual('0xb');
});
it('should prefix the result with 0x', function () {
it('should prefix the result with 0x', () => {
const increasedGasPrice = utils.increaseLastGasPrice('a');
assert.strictEqual(increasedGasPrice, '0xb');
expect(increasedGasPrice).toStrictEqual('0xb');
});
});
describe('hexGreaterThan', function () {
it('should return true if the first value is greater than the second value', function () {
assert.strictEqual(utils.hexGreaterThan('0xb', '0xa'), true);
describe('hexGreaterThan', () => {
it('should return true if the first value is greater than the second value', () => {
expect(utils.hexGreaterThan('0xb', '0xa')).toStrictEqual(true);
});
it('should return false if the first value is less than the second value', function () {
assert.strictEqual(utils.hexGreaterThan('0xa', '0xb'), false);
it('should return false if the first value is less than the second value', () => {
expect(utils.hexGreaterThan('0xa', '0xb')).toStrictEqual(false);
});
it('should return false if the first value is equal to the second value', function () {
assert.strictEqual(utils.hexGreaterThan('0xa', '0xa'), false);
it('should return false if the first value is equal to the second value', () => {
expect(utils.hexGreaterThan('0xa', '0xa')).toStrictEqual(false);
});
it('should correctly compare prefixed and non-prefixed hex values', function () {
assert.strictEqual(utils.hexGreaterThan('0xb', 'a'), true);
it('should correctly compare prefixed and non-prefixed hex values', () => {
expect(utils.hexGreaterThan('0xb', 'a')).toStrictEqual(true);
});
});
describe('getHexGasTotal', function () {
it('should multiply the hex gasLimit and hex gasPrice values together', function () {
assert.strictEqual(
describe('getHexGasTotal', () => {
it('should multiply the hex gasLimit and hex gasPrice values together', () => {
expect(
utils.getHexGasTotal({ gasLimit: '0x5208', gasPrice: '0x3b9aca00' }),
'0x1319718a5000',
);
).toStrictEqual('0x1319718a5000');
});
it('should prefix the result with 0x', function () {
assert.strictEqual(
it('should prefix the result with 0x', () => {
expect(
utils.getHexGasTotal({ gasLimit: '5208', gasPrice: '3b9aca00' }),
'0x1319718a5000',
);
).toStrictEqual('0x1319718a5000');
});
});
describe('addEth', function () {
it('should add two values together rounding to 6 decimal places', function () {
assert.strictEqual(utils.addEth('0.12345678', '0'), '0.123457');
describe('addEth', () => {
it('should add two values together rounding to 6 decimal places', () => {
expect(utils.addEth('0.12345678', '0')).toStrictEqual('0.123457');
});
it('should add any number of values together rounding to 6 decimal places', function () {
assert.strictEqual(
it('should add any number of values together rounding to 6 decimal places', () => {
expect(
utils.addEth(
'0.1',
'0.02',
@ -64,18 +61,17 @@ describe('Confirm Transaction utils', function () {
'0.000006',
'0.0000007',
),
'0.123457',
);
).toStrictEqual('0.123457');
});
});
describe('addFiat', function () {
it('should add two values together rounding to 2 decimal places', function () {
assert.strictEqual(utils.addFiat('0.12345678', '0'), '0.12');
describe('addFiat', () => {
it('should add two values together rounding to 2 decimal places', () => {
expect(utils.addFiat('0.12345678', '0')).toStrictEqual('0.12');
});
it('should add any number of values together rounding to 2 decimal places', function () {
assert.strictEqual(
it('should add any number of values together rounding to 2 decimal places', () => {
expect(
utils.addFiat(
'0.1',
'0.02',
@ -85,13 +81,12 @@ describe('Confirm Transaction utils', function () {
'0.000006',
'0.0000007',
),
'0.12',
);
).toStrictEqual('0.12');
});
});
describe('getValueFromWeiHex', function () {
it('should get the transaction amount in ETH', function () {
describe('getValueFromWeiHex', () => {
it('should get the transaction amount in ETH', () => {
const ethTransactionAmount = utils.getValueFromWeiHex({
value: '0xde0b6b3a7640000',
toCurrency: 'ETH',
@ -99,10 +94,10 @@ describe('Confirm Transaction utils', function () {
numberOfDecimals: 6,
});
assert.strictEqual(ethTransactionAmount, '1');
expect(ethTransactionAmount).toStrictEqual('1');
});
it('should get the transaction amount in fiat', function () {
it('should get the transaction amount in fiat', () => {
const fiatTransactionAmount = utils.getValueFromWeiHex({
value: '0xde0b6b3a7640000',
toCurrency: 'usd',
@ -110,12 +105,12 @@ describe('Confirm Transaction utils', function () {
numberOfDecimals: 2,
});
assert.strictEqual(fiatTransactionAmount, '468.58');
expect(fiatTransactionAmount).toStrictEqual('468.58');
});
});
describe('getTransactionFee', function () {
it('should get the transaction fee in ETH', function () {
describe('getTransactionFee', () => {
it('should get the transaction fee in ETH', () => {
const ethTransactionFee = utils.getTransactionFee({
value: '0x1319718a5000',
toCurrency: 'ETH',
@ -123,10 +118,10 @@ describe('Confirm Transaction utils', function () {
numberOfDecimals: 6,
});
assert.strictEqual(ethTransactionFee, '0.000021');
expect(ethTransactionFee).toStrictEqual('0.000021');
});
it('should get the transaction fee in fiat', function () {
it('should get the transaction fee in fiat', () => {
const fiatTransactionFee = utils.getTransactionFee({
value: '0x1319718a5000',
toCurrency: 'usd',
@ -134,14 +129,14 @@ describe('Confirm Transaction utils', function () {
numberOfDecimals: 2,
});
assert.strictEqual(fiatTransactionFee, '0.01');
expect(fiatTransactionFee).toStrictEqual('0.01');
});
});
describe('formatCurrency', function () {
it('should format USD values', function () {
describe('formatCurrency', () => {
it('should format USD values', () => {
const value = utils.formatCurrency('123.45', 'usd');
assert.strictEqual(value, '$123.45');
expect(value).toStrictEqual('$123.45');
});
});
});

View File

@ -1,36 +1,35 @@
import assert from 'assert';
import BigNumber from 'bignumber.js';
import { addCurrencies, conversionUtil } from './conversion-util';
describe('conversion utils', function () {
describe('addCurrencies()', function () {
it('add whole numbers', function () {
describe('conversion utils', () => {
describe('addCurrencies()', () => {
it('add whole numbers', () => {
const result = addCurrencies(3, 9, {
aBase: 10,
bBase: 10,
});
assert.strictEqual(result.toNumber(), 12);
expect(result.toNumber()).toStrictEqual(12);
});
it('add decimals', function () {
it('add decimals', () => {
const result = addCurrencies(1.3, 1.9, {
aBase: 10,
bBase: 10,
});
assert.strictEqual(result.toNumber(), 3.2);
expect(result.toNumber()).toStrictEqual(3.2);
});
it('add repeating decimals', function () {
it('add repeating decimals', () => {
const result = addCurrencies(1 / 3, 1 / 9, {
aBase: 10,
bBase: 10,
});
assert.strictEqual(result.toNumber(), 0.4444444444444444);
expect(result.toNumber()).toStrictEqual(0.4444444444444444);
});
});
describe('conversionUtil', function () {
it('Returns expected types', function () {
describe('conversionUtil', () => {
it('returns expected types', () => {
const conv1 = conversionUtil(1000000000000000000, {
fromNumericBase: 'dec',
toNumericBase: 'hex',
@ -40,102 +39,89 @@ describe('conversion utils', function () {
fromDenomination: 'ETH',
toDenomination: 'WEI',
});
assert(
typeof conv1 === 'string',
'conversion 1 should return type string',
);
assert(conv2 instanceof BigNumber, 'conversion 2 should be a BigNumber');
expect(typeof conv1 === 'string').toStrictEqual(true);
expect(conv2 instanceof BigNumber).toStrictEqual(true);
});
it('Converts from dec to hex', function () {
assert.strictEqual(
it('converts from dec to hex', () => {
expect(
conversionUtil('1000000000000000000', {
fromNumericBase: 'dec',
toNumericBase: 'hex',
}),
'de0b6b3a7640000',
);
assert.strictEqual(
).toStrictEqual('de0b6b3a7640000');
expect(
conversionUtil('1500000000000000000', {
fromNumericBase: 'dec',
toNumericBase: 'hex',
}),
'14d1120d7b160000',
);
).toStrictEqual('14d1120d7b160000');
});
it('Converts hex formatted numbers to dec', function () {
assert.strictEqual(
it('converts hex formatted numbers to dec', () => {
expect(
conversionUtil('0xde0b6b3a7640000', {
fromNumericBase: 'hex',
toNumericBase: 'dec',
}),
'1000000000000000000',
);
assert.strictEqual(
).toStrictEqual('1000000000000000000');
expect(
conversionUtil('0x14d1120d7b160000', {
fromNumericBase: 'hex',
toNumericBase: 'dec',
}),
'1500000000000000000',
);
).toStrictEqual('1500000000000000000');
});
it('Converts WEI to ETH', function () {
assert.strictEqual(
it('converts WEI to ETH', () => {
expect(
conversionUtil('0xde0b6b3a7640000', {
fromNumericBase: 'hex',
toNumericBase: 'dec',
fromDenomination: 'WEI',
toDenomination: 'ETH',
}),
'1',
);
assert.strictEqual(
).toStrictEqual('1');
expect(
conversionUtil('0x14d1120d7b160000', {
fromNumericBase: 'hex',
toNumericBase: 'dec',
fromDenomination: 'WEI',
toDenomination: 'ETH',
}),
'1.5',
);
).toStrictEqual('1.5');
});
it('Converts ETH to WEI', function () {
assert.strictEqual(
it('converts ETH to WEI', () => {
expect(
conversionUtil('1', {
fromNumericBase: 'dec',
fromDenomination: 'ETH',
toDenomination: 'WEI',
}).toNumber(),
1000000000000000000,
);
assert.strictEqual(
).toStrictEqual(1000000000000000000);
expect(
conversionUtil('1.5', {
fromNumericBase: 'dec',
fromDenomination: 'ETH',
toDenomination: 'WEI',
}).toNumber(),
1500000000000000000,
);
).toStrictEqual(1500000000000000000);
});
it('Converts ETH to GWEI', function () {
assert.strictEqual(
it('converts ETH to GWEI', () => {
expect(
conversionUtil('1', {
fromNumericBase: 'dec',
fromDenomination: 'ETH',
toDenomination: 'GWEI',
}).toNumber(),
1000000000,
);
assert.strictEqual(
).toStrictEqual(1000000000);
expect(
conversionUtil('1.5', {
fromNumericBase: 'dec',
fromDenomination: 'ETH',
toDenomination: 'GWEI',
}).toNumber(),
1500000000,
);
).toStrictEqual(1500000000);
});
it('Converts ETH to USD', function () {
assert.strictEqual(
it('converts ETH to USD', () => {
expect(
conversionUtil('1', {
fromNumericBase: 'dec',
toNumericBase: 'dec',
@ -143,9 +129,8 @@ describe('conversion utils', function () {
conversionRate: 468.58,
numberOfDecimals: 2,
}),
'468.58',
);
assert.strictEqual(
).toStrictEqual('468.58');
expect(
conversionUtil('1.5', {
fromNumericBase: 'dec',
toNumericBase: 'dec',
@ -153,11 +138,10 @@ describe('conversion utils', function () {
conversionRate: 468.58,
numberOfDecimals: 2,
}),
'702.87',
);
).toStrictEqual('702.87');
});
it('Converts USD to ETH', function () {
assert.strictEqual(
it('converts USD to ETH', () => {
expect(
conversionUtil('468.58', {
fromNumericBase: 'dec',
toNumericBase: 'dec',
@ -166,9 +150,8 @@ describe('conversion utils', function () {
numberOfDecimals: 2,
invertConversionRate: true,
}),
'1',
);
assert.strictEqual(
).toStrictEqual('1');
expect(
conversionUtil('702.87', {
fromNumericBase: 'dec',
toNumericBase: 'dec',
@ -177,8 +160,7 @@ describe('conversion utils', function () {
numberOfDecimals: 2,
invertConversionRate: true,
}),
'1.5',
);
).toStrictEqual('1.5');
});
});
});

View File

@ -1,43 +1,42 @@
import assert from 'assert';
import { ETH } from '../constants/common';
import * as utils from './conversions.util';
describe('conversion utils', function () {
describe('getWeiHexFromDecimalValue', function () {
it('should correctly convert 0 in ETH', function () {
describe('conversion utils', () => {
describe('getWeiHexFromDecimalValue', () => {
it('should correctly convert 0 in ETH', () => {
const weiValue = utils.getWeiHexFromDecimalValue({
value: '0',
fromCurrency: ETH,
fromDenomination: ETH,
});
assert.strictEqual(weiValue, '0');
expect(weiValue).toStrictEqual('0');
});
});
describe('decETHToDecWEI', function () {
it('should correctly convert 1 ETH to WEI', function () {
describe('decETHToDecWEI', () => {
it('should correctly convert 1 ETH to WEI', () => {
const weiValue = utils.decETHToDecWEI('1');
assert.strictEqual(weiValue, '1000000000000000000');
expect(weiValue).toStrictEqual('1000000000000000000');
});
it('should correctly convert 0.000000000000000001 ETH to WEI', function () {
it('should correctly convert 0.000000000000000001 ETH to WEI', () => {
const weiValue = utils.decETHToDecWEI('0.000000000000000001');
assert.strictEqual(weiValue, '1');
expect(weiValue).toStrictEqual('1');
});
it('should correctly convert 1000000.000000000000000001 ETH to WEI', function () {
it('should correctly convert 1000000.000000000000000001 ETH to WEI', () => {
const weiValue = utils.decETHToDecWEI('1000000.000000000000000001');
assert.strictEqual(weiValue, '1000000000000000000000001');
expect(weiValue).toStrictEqual('1000000000000000000000001');
});
it('should correctly convert 9876.543210 ETH to WEI', function () {
it('should correctly convert 9876.543210 ETH to WEI', () => {
const weiValue = utils.decETHToDecWEI('9876.543210');
assert.strictEqual(weiValue, '9876543210000000000000');
expect(weiValue).toStrictEqual('9876543210000000000000');
});
it('should correctly convert 1.0000000000000000 ETH to WEI', function () {
it('should correctly convert 1.0000000000000000 ETH to WEI', () => {
const weiValue = utils.decETHToDecWEI('1.0000000000000000');
assert.strictEqual(weiValue, '1000000000000000000');
expect(weiValue).toStrictEqual('1000000000000000000');
});
});
});

View File

@ -1,24 +1,22 @@
import assert from 'assert';
import nock from 'nock';
import sinon from 'sinon';
import proxyquire from 'proxyquire';
const fakeStorage = {};
const fetchWithCache = proxyquire('./fetch-with-cache', {
'../../../lib/storage-helpers': fakeStorage,
}).default;
import { getStorageItem, setStorageItem } from '../../../lib/storage-helpers';
describe('Fetch with cache', function () {
beforeEach(function () {
fakeStorage.getStorageItem = sinon.stub();
fakeStorage.setStorageItem = sinon.stub();
});
afterEach(function () {
jest.mock('../../../lib/storage-helpers.js', () => ({
getStorageItem: jest.fn(),
setStorageItem: jest.fn(),
}));
const fetchWithCache = require('./fetch-with-cache').default;
describe('Fetch with cache', () => {
afterEach(() => {
sinon.restore();
nock.cleanAll();
});
it('fetches a url', async function () {
it('fetches a url', async () => {
nock('https://fetchwithcache.metamask.io')
.get('/price')
.reply(200, '{"average": 1}');
@ -26,17 +24,17 @@ describe('Fetch with cache', function () {
const response = await fetchWithCache(
'https://fetchwithcache.metamask.io/price',
);
assert.deepStrictEqual(response, {
expect(response).toStrictEqual({
average: 1,
});
});
it('returns cached response', async function () {
it('returns cached response', async () => {
nock('https://fetchwithcache.metamask.io')
.get('/price')
.reply(200, '{"average": 2}');
fakeStorage.getStorageItem.returns({
getStorageItem.mockReturnValueOnce({
cachedResponse: { average: 1 },
cachedTime: Date.now(),
});
@ -44,17 +42,17 @@ describe('Fetch with cache', function () {
const response = await fetchWithCache(
'https://fetchwithcache.metamask.io/price',
);
assert.deepStrictEqual(response, {
expect(response).toStrictEqual({
average: 1,
});
});
it('fetches URL again after cache refresh time has passed', async function () {
it('fetches URL again after cache refresh time has passed', async () => {
nock('https://fetchwithcache.metamask.io')
.get('/price')
.reply(200, '{"average": 3}');
fakeStorage.getStorageItem.returns({
getStorageItem.mockReturnValueOnce({
cachedResponse: { average: 1 },
cachedTime: Date.now() - 1000,
});
@ -64,85 +62,84 @@ describe('Fetch with cache', function () {
{},
{ cacheRefreshTime: 123 },
);
assert.deepStrictEqual(response, {
expect(response).toStrictEqual({
average: 3,
});
});
it('should abort the request when the custom timeout is hit', async function () {
it('should abort the request when the custom timeout is hit', async () => {
nock('https://fetchwithcache.metamask.io')
.get('/price')
.delay(100)
.reply(200, '{"average": 4}');
await assert.rejects(
() =>
fetchWithCache(
'https://fetchwithcache.metamask.io/price',
{},
{ timeout: 20 },
),
{ name: 'AbortError', message: 'Aborted' },
);
await expect(() =>
fetchWithCache(
'https://fetchwithcache.metamask.io/price',
{},
{ timeout: 20 },
),
).rejects.toThrow({ name: 'AbortError', message: 'Aborted' });
});
it('throws when the response is unsuccessful', async function () {
it('throws when the response is unsuccessful', async () => {
nock('https://fetchwithcache.metamask.io')
.get('/price')
.reply(500, '{"average": 6}');
await assert.rejects(() =>
await expect(() =>
fetchWithCache('https://fetchwithcache.metamask.io/price'),
);
).rejects.toThrow('');
});
it('throws when a POST request is attempted', async function () {
it('throws when a POST request is attempted', async () => {
nock('https://fetchwithcache.metamask.io')
.post('/price')
.reply(200, '{"average": 7}');
await assert.rejects(() =>
await expect(() =>
fetchWithCache('https://fetchwithcache.metamask.io/price', {
method: 'POST',
}),
);
).rejects.toThrow('');
});
it('throws when the request has a truthy body', async function () {
it('throws when the request has a truthy body', async () => {
nock('https://fetchwithcache.metamask.io')
.get('/price')
.reply(200, '{"average": 8}');
await assert.rejects(() =>
await expect(() =>
fetchWithCache('https://fetchwithcache.metamask.io/price', { body: 1 }),
);
).rejects.toThrow('');
});
it('throws when the request has an invalid Content-Type header', async function () {
it('throws when the request has an invalid Content-Type header', async () => {
nock('https://fetchwithcache.metamask.io')
.get('/price')
.reply(200, '{"average": 9}');
await assert.rejects(
() =>
fetchWithCache('https://fetchwithcache.metamask.io/price', {
headers: { 'Content-Type': 'text/plain' },
}),
{ message: 'fetchWithCache only supports JSON responses' },
);
await expect(() =>
fetchWithCache('https://fetchwithcache.metamask.io/price', {
headers: { 'Content-Type': 'text/plain' },
}),
).rejects.toThrow({
message: 'fetchWithCache only supports JSON responses',
});
});
it('should correctly cache responses from interwoven requests', async function () {
it('should correctly cache responses from interwoven requests', async () => {
nock('https://fetchwithcache.metamask.io')
.get('/foo')
.reply(200, '{"average": 9}');
nock('https://fetchwithcache.metamask.io')
.get('/bar')
.reply(200, '{"average": 9}');
const testCache = {};
fakeStorage.getStorageItem.callsFake((key) => testCache[key]);
fakeStorage.setStorageItem.callsFake((key, value) => {
getStorageItem.mockImplementation((key) => testCache[key]);
setStorageItem.mockImplementation((key, value) => {
testCache[key] = value;
});
@ -159,15 +156,13 @@ describe('Fetch with cache', function () {
),
]);
assert.deepStrictEqual(
expect(
testCache['cachedFetch:https://fetchwithcache.metamask.io/foo']
.cachedResponse,
{ average: 9 },
);
assert.deepStrictEqual(
).toStrictEqual({ average: 9 });
expect(
testCache['cachedFetch:https://fetchwithcache.metamask.io/bar']
.cachedResponse,
{ average: 9 },
);
).toStrictEqual({ average: 9 });
});
});

View File

@ -1,9 +1,8 @@
import assert from 'assert';
import React from 'react';
import { shallow } from 'enzyme';
import { getMessage } from './i18n-helper';
describe('i18n helper', function () {
describe('i18n helper', () => {
const TEST_LOCALE_CODE = 'TEST_LOCALE_CODE';
const TEST_KEY_1 = 'TEST_KEY_1';
@ -97,29 +96,27 @@ describe('i18n helper', function () {
</div>
);
describe('getMessage', function () {
it('should return the exact message paired with key if there are no substitutions', function () {
describe('getMessage', () => {
it('should return the exact message paired with key if there are no substitutions', () => {
const result = t(TEST_KEY_1);
assert.strictEqual(result, 'This is a simple message.');
expect(result).toStrictEqual('This is a simple message.');
});
it('should return the correct message when a single non-react substitution is made', function () {
it('should return the correct message when a single non-react substitution is made', () => {
const result = t(TEST_KEY_2, [TEST_SUBSTITUTION_1]);
assert.strictEqual(
result,
expect(result).toStrictEqual(
`This is a message with a single non-react substitution ${TEST_SUBSTITUTION_1}.`,
);
});
it('should return the correct message when two non-react substitutions are made', function () {
it('should return the correct message when two non-react substitutions are made', () => {
const result = t(TEST_KEY_3, [TEST_SUBSTITUTION_1, TEST_SUBSTITUTION_2]);
assert.strictEqual(
result,
expect(result).toStrictEqual(
`This is a message with two non-react substitutions ${TEST_SUBSTITUTION_1} and ${TEST_SUBSTITUTION_2}.`,
);
});
it('should return the correct message when multiple non-react substitutions are made', function () {
it('should return the correct message when multiple non-react substitutions are made', () => {
const result = t(TEST_KEY_4, [
TEST_SUBSTITUTION_1,
TEST_SUBSTITUTION_2,
@ -127,50 +124,46 @@ describe('i18n helper', function () {
TEST_SUBSTITUTION_4,
TEST_SUBSTITUTION_5,
]);
assert.strictEqual(
result,
expect(result).toStrictEqual(
`${TEST_SUBSTITUTION_1} - ${TEST_SUBSTITUTION_2} - ${TEST_SUBSTITUTION_3} - ${TEST_SUBSTITUTION_4} - ${TEST_SUBSTITUTION_5}`,
);
});
it('should correctly render falsey substitutions', function () {
it('should correctly render falsey substitutions', () => {
const result = t(TEST_KEY_4, [0, -0, '', false, NaN]);
assert.strictEqual(result, '0 - 0 - - false - NaN');
expect(result).toStrictEqual('0 - 0 - - false - NaN');
});
it('should render nothing for "null" and "undefined" substitutions', function () {
it('should render nothing for "null" and "undefined" substitutions', () => {
const result = t(TEST_KEY_5, [null, TEST_SUBSTITUTION_2]);
assert.strictEqual(result, ` - ${TEST_SUBSTITUTION_2} - `);
expect(result).toStrictEqual(` - ${TEST_SUBSTITUTION_2} - `);
});
it('should return the correct message when a single react substitution is made', function () {
it('should return the correct message when a single react substitution is made', () => {
const result = t(TEST_KEY_6, [TEST_SUBSTITUTION_6]);
assert.strictEqual(
shallow(result).html(),
expect(shallow(result).html()).toStrictEqual(
'<span> Testing a react substitution <div style="color:red">TEST_SUBSTITUTION_1</div>. </span>',
);
});
it('should return the correct message when two react substitutions are made', function () {
it('should return the correct message when two react substitutions are made', () => {
const result = t(TEST_KEY_7, [
TEST_SUBSTITUTION_7_1,
TEST_SUBSTITUTION_7_2,
]);
assert.strictEqual(
shallow(result).html(),
expect(shallow(result).html()).toStrictEqual(
'<span> Testing a react substitution <div style="color:red">TEST_SUBSTITUTION_1</div> and another <div style="color:blue">TEST_SUBSTITUTION_2</div>. </span>',
);
});
it('should return the correct message when substituting a mix of react elements and strings', function () {
it('should return the correct message when substituting a mix of react elements and strings', () => {
const result = t(TEST_KEY_8, [
TEST_SUBSTITUTION_1,
TEST_SUBSTITUTION_8_1,
TEST_SUBSTITUTION_2,
TEST_SUBSTITUTION_8_2,
]);
assert.strictEqual(
shallow(result).html(),
expect(shallow(result).html()).toStrictEqual(
'<span> Testing a mix TEST_SUBSTITUTION_1 of react substitutions <div style="color:orange">TEST_SUBSTITUTION_3</div> and string substitutions TEST_SUBSTITUTION_2 + <div style="color:pink">TEST_SUBSTITUTION_4</div>. </span>',
);
});

View File

@ -1,4 +1,3 @@
import assert from 'assert';
import {
TRANSACTION_TYPES,
TRANSACTION_GROUP_STATUSES,
@ -6,28 +5,28 @@ import {
} from '../../../../shared/constants/transaction';
import * as utils from './transactions.util';
describe('Transactions utils', function () {
describe('getTokenData', function () {
it('should return token data', function () {
describe('Transactions utils', () => {
describe('getTokenData', () => {
it('should return token data', () => {
const tokenData = utils.getTokenData(
'0xa9059cbb00000000000000000000000050a9d56c2b8ba9a5c7f2c08c3d26e0499f23a7060000000000000000000000000000000000000000000000000000000000004e20',
);
assert.ok(tokenData);
expect(tokenData).toStrictEqual(expect.anything());
const { name, args } = tokenData;
assert.strictEqual(name, TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER);
expect(name).toStrictEqual(TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER);
const to = args._to;
const value = args._value.toString();
assert.strictEqual(to, '0x50A9D56C2B8BA9A5c7f2C08C3d26E0499F23a706');
assert.strictEqual(value, '20000');
expect(to).toStrictEqual('0x50A9D56C2B8BA9A5c7f2C08C3d26E0499F23a706');
expect(value).toStrictEqual('20000');
});
it('should not throw errors when called without arguments', function () {
assert.doesNotThrow(() => utils.getTokenData());
it('should not throw errors when called without arguments', () => {
expect(() => utils.getTokenData()).not.toThrow();
});
});
describe('getStatusKey', function () {
it('should return the correct status', function () {
describe('getStatusKey', () => {
it('should return the correct status', () => {
const tests = [
{
transaction: {
@ -56,7 +55,7 @@ describe('Transactions utils', function () {
];
tests.forEach(({ transaction, expected }) => {
assert.strictEqual(utils.getStatusKey(transaction), expected);
expect(utils.getStatusKey(transaction)).toStrictEqual(expected);
});
});
});

View File

@ -1,252 +1,248 @@
import assert from 'assert';
import ethUtil from 'ethereumjs-util';
import * as util from './util';
describe('util', function () {
describe('util', () => {
let ethInWei = '1';
for (let i = 0; i < 18; i++) {
ethInWei += '0';
}
describe('#parseBalance', function () {
it('should render 0.01 eth correctly', function () {
describe('#parseBalance', () => {
it('should render 0.01 eth correctly', () => {
const input = '0x2386F26FC10000';
const output = util.parseBalance(input);
assert.deepStrictEqual(output, ['0', '01']);
expect(output).toStrictEqual(['0', '01']);
});
it('should render 12.023 eth correctly', function () {
it('should render 12.023 eth correctly', () => {
const input = 'A6DA46CCA6858000';
const output = util.parseBalance(input);
assert.deepStrictEqual(output, ['12', '023']);
expect(output).toStrictEqual(['12', '023']);
});
it('should render 0.0000000342422 eth correctly', function () {
it('should render 0.0000000342422 eth correctly', () => {
const input = '0x7F8FE81C0';
const output = util.parseBalance(input);
assert.deepStrictEqual(output, ['0', '0000000342422']);
expect(output).toStrictEqual(['0', '0000000342422']);
});
it('should render 0 eth correctly', function () {
it('should render 0 eth correctly', () => {
const input = '0x0';
const output = util.parseBalance(input);
assert.deepStrictEqual(output, ['0', '0']);
expect(output).toStrictEqual(['0', '0']);
});
});
describe('#addressSummary', function () {
it('should add case-sensitive checksum', function () {
describe('#addressSummary', () => {
it('should add case-sensitive checksum', () => {
const address = '0xfdea65c8e26263f6d9a1b5de9555d2931a33b825';
const result = util.addressSummary(address);
assert.strictEqual(result, '0xFDEa65C8...b825');
expect(result).toStrictEqual('0xFDEa65C8...b825');
});
it('should accept arguments for firstseg, lastseg, and keepPrefix', function () {
it('should accept arguments for firstseg, lastseg, and keepPrefix', () => {
const address = '0xfdea65c8e26263f6d9a1b5de9555d2931a33b825';
const result = util.addressSummary(address, 4, 4, false);
assert.strictEqual(result, 'FDEa...b825');
expect(result).toStrictEqual('FDEa...b825');
});
});
describe('#isValidAddress', function () {
it('should allow 40-char non-prefixed hex', function () {
describe('#isValidAddress', () => {
it('should allow 40-char non-prefixed hex', () => {
const address = 'fdea65c8e26263f6d9a1b5de9555d2931a33b825';
const result = util.isValidAddress(address);
assert.ok(result);
expect(result).toStrictEqual(true);
});
it('should allow 42-char non-prefixed hex', function () {
it('should allow 42-char non-prefixed hex', () => {
const address = '0xfdea65c8e26263f6d9a1b5de9555d2931a33b825';
const result = util.isValidAddress(address);
assert.ok(result);
expect(result).toStrictEqual(true);
});
it('should not allow less non hex-prefixed', function () {
it('should not allow less non hex-prefixed', () => {
const address = 'fdea65c8e26263f6d9a1b5de9555d2931a33b85';
const result = util.isValidAddress(address);
assert.ok(!result);
expect(result).toStrictEqual(false);
});
it('should not allow less hex-prefixed', function () {
it('should not allow less hex-prefixed', () => {
const address = '0xfdea65ce26263f6d9a1b5de9555d2931a33b85';
const result = util.isValidAddress(address);
assert.ok(!result);
expect(result).toStrictEqual(false);
});
it('should recognize correct capitalized checksum', function () {
it('should recognize correct capitalized checksum', () => {
const address = '0xFDEa65C8e26263F6d9A1B5de9555D2931A33b825';
const result = util.isValidAddress(address);
assert.ok(result);
expect(result).toStrictEqual(true);
});
it('should recognize incorrect capitalized checksum', function () {
it('should recognize incorrect capitalized checksum', () => {
const address = '0xFDea65C8e26263F6d9A1B5de9555D2931A33b825';
const result = util.isValidAddress(address);
assert.ok(!result);
expect(result).toStrictEqual(false);
});
it('should recognize this sample hashed address', function () {
it('should recognize this sample hashed address', () => {
const address = '0x5Fda30Bb72B8Dfe20e48A00dFc108d0915BE9Bb0';
const result = util.isValidAddress(address);
const hashed = ethUtil.toChecksumAddress(address.toLowerCase());
assert.strictEqual(hashed, address, 'example is hashed correctly');
assert.ok(result, 'is valid by our check');
expect(hashed).toStrictEqual(address);
expect(result).toStrictEqual(true);
});
});
describe('isValidDomainName', function () {
it('should return true when given a valid domain name', function () {
assert.strictEqual(util.isValidDomainName('foo.bar'), true);
describe('isValidDomainName', () => {
it('should return true when given a valid domain name', () => {
expect(util.isValidDomainName('foo.bar')).toStrictEqual(true);
});
it('should return true when given a valid subdomain', function () {
assert.strictEqual(util.isValidDomainName('foo.foo.bar'), true);
it('should return true when given a valid subdomain', () => {
expect(util.isValidDomainName('foo.foo.bar')).toStrictEqual(true);
});
it('should return true when given a single-character domain', function () {
assert.strictEqual(util.isValidDomainName('f.bar'), true);
it('should return true when given a single-character domain', () => {
expect(util.isValidDomainName('f.bar')).toStrictEqual(true);
});
it('should return true when given a unicode TLD', function () {
assert.strictEqual(util.isValidDomainName('台灣.中国'), true);
it('should return true when given a unicode TLD', () => {
expect(util.isValidDomainName('台灣.中国')).toStrictEqual(true);
});
it('should return false when given a domain with unacceptable ASCII characters', function () {
assert.strictEqual(util.isValidDomainName('$.bar'), false);
it('should return false when given a domain with unacceptable ASCII characters', () => {
expect(util.isValidDomainName('$.bar')).toStrictEqual(false);
});
it('should return false when given a TLD that starts with a dash', function () {
assert.strictEqual(util.isValidDomainName('foo.-bar'), false);
it('should return false when given a TLD that starts with a dash', () => {
expect(util.isValidDomainName('foo.-bar')).toStrictEqual(false);
});
it('should return false when given a TLD that ends with a dash', function () {
assert.strictEqual(util.isValidDomainName('foo.bar-'), false);
it('should return false when given a TLD that ends with a dash', () => {
expect(util.isValidDomainName('foo.bar-')).toStrictEqual(false);
});
it('should return false when given a domain name with a chunk that starts with a dash', function () {
assert.strictEqual(util.isValidDomainName('-foo.bar'), false);
it('should return false when given a domain name with a chunk that starts with a dash', () => {
expect(util.isValidDomainName('-foo.bar')).toStrictEqual(false);
});
it('should return false when given a domain name with a chunk that ends with a dash', function () {
assert.strictEqual(util.isValidDomainName('foo-.bar'), false);
it('should return false when given a domain name with a chunk that ends with a dash', () => {
expect(util.isValidDomainName('foo-.bar')).toStrictEqual(false);
});
it('should return false when given a bare TLD', function () {
assert.strictEqual(util.isValidDomainName('bar'), false);
it('should return false when given a bare TLD', () => {
expect(util.isValidDomainName('bar')).toStrictEqual(false);
});
it('should return false when given a domain that starts with a period', function () {
assert.strictEqual(util.isValidDomainName('.bar'), false);
it('should return false when given a domain that starts with a period', () => {
expect(util.isValidDomainName('.bar')).toStrictEqual(false);
});
it('should return false when given a subdomain that starts with a period', function () {
assert.strictEqual(util.isValidDomainName('.foo.bar'), false);
it('should return false when given a subdomain that starts with a period', () => {
expect(util.isValidDomainName('.foo.bar')).toStrictEqual(false);
});
it('should return false when given a domain that ends with a period', function () {
assert.strictEqual(util.isValidDomainName('bar.'), false);
it('should return false when given a domain that ends with a period', () => {
expect(util.isValidDomainName('bar.')).toStrictEqual(false);
});
it('should return false when given a 1-character TLD', function () {
assert.strictEqual(util.isValidDomainName('foo.b'), false);
it('should return false when given a 1-character TLD', () => {
expect(util.isValidDomainName('foo.b')).toStrictEqual(false);
});
});
describe('isOriginContractAddress', function () {
it('should return true when the send address is the same as the selected tokens contract address', function () {
assert.equal(
describe('isOriginContractAddress', () => {
it('should return true when the send address is the same as the selected tokens contract address', () => {
expect(
util.isOriginContractAddress(
'0x8d6b81208414189a58339873ab429b6c47ab92d3',
'0x8d6b81208414189a58339873ab429b6c47ab92d3',
),
true,
);
).toStrictEqual(true);
});
it('should return true when the send address is the same as the selected tokens contract address, capitalized input', function () {
assert.equal(
it('should return true when the send address is the same as the selected tokens contract address, capitalized input', () => {
expect(
util.isOriginContractAddress(
'0x8d6b81208414189a58339873ab429b6c47ab92d3',
'0X8D6B81208414189A58339873AB429B6C47AB92D3',
),
true,
);
).toStrictEqual(true);
});
it('should return false when the recipient address differs', function () {
assert.equal(
it('should return false when the recipient address differs', () => {
expect(
util.isOriginContractAddress(
'0x8d6b81208414189a58339873ab429b6c47ab92d3',
'0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B',
),
false,
);
).toStrictEqual(false);
});
});
describe('#numericBalance', function () {
it('should return a BN 0 if given nothing', function () {
describe('#numericBalance', () => {
it('should return a BN 0 if given nothing', () => {
const result = util.numericBalance();
assert.strictEqual(result.toString(10), '0');
expect(result.toString(10)).toStrictEqual('0');
});
it('should work with hex prefix', function () {
it('should work with hex prefix', () => {
const result = util.numericBalance('0x012');
assert.strictEqual(result.toString(10), '18');
expect(result.toString(10)).toStrictEqual('18');
});
it('should work with no hex prefix', function () {
it('should work with no hex prefix', () => {
const result = util.numericBalance('012');
assert.strictEqual(result.toString(10), '18');
expect(result.toString(10)).toStrictEqual('18');
});
});
describe('#formatBalance', function () {
it('should return None when given nothing', function () {
describe('#formatBalance', () => {
it('should return None when given nothing', () => {
const result = util.formatBalance();
assert.strictEqual(result, 'None', 'should return "None"');
expect(result).toStrictEqual('None', 'should return "None"');
});
it('should return 1.0000 ETH', function () {
it('should return 1.0000 ETH', () => {
const input = new ethUtil.BN(ethInWei, 10).toJSON();
const result = util.formatBalance(input, 4);
assert.strictEqual(result, '1.0000 ETH');
expect(result).toStrictEqual('1.0000 ETH');
});
it('should return 0.500 ETH', function () {
it('should return 0.500 ETH', () => {
const input = new ethUtil.BN(ethInWei, 10)
.div(new ethUtil.BN('2', 10))
.toJSON();
const result = util.formatBalance(input, 3);
assert.strictEqual(result, '0.500 ETH');
expect(result).toStrictEqual('0.500 ETH');
});
it('should display specified decimal points', function () {
it('should display specified decimal points', () => {
const input = '0x128dfa6a90b28000';
const result = util.formatBalance(input, 2);
assert.strictEqual(result, '1.33 ETH');
expect(result).toStrictEqual('1.33 ETH');
});
it('should default to 3 decimal points', function () {
it('should default to 3 decimal points', () => {
const input = '0x128dfa6a90b28000';
const result = util.formatBalance(input);
assert.strictEqual(result, '1.337 ETH');
expect(result).toStrictEqual('1.337 ETH');
});
it('should show 2 significant digits for tiny balances', function () {
it('should show 2 significant digits for tiny balances', () => {
const input = '0x1230fa6a90b28';
const result = util.formatBalance(input);
assert.strictEqual(result, '0.00032 ETH');
expect(result).toStrictEqual('0.00032 ETH');
});
it('should not parse the balance and return value with 2 decimal points with ETH at the end', function () {
it('should not parse the balance and return value with 2 decimal points with ETH at the end', () => {
const value = '1.2456789';
const needsParse = false;
const result = util.formatBalance(value, 2, needsParse);
assert.strictEqual(result, '1.24 ETH');
expect(result).toStrictEqual('1.24 ETH');
});
});
describe('normalizing values', function () {
describe('#normalizeToWei', function () {
it('should convert an eth to the appropriate equivalent values', function () {
describe('normalizing values', () => {
describe('#normalizeToWei', () => {
it('should convert an eth to the appropriate equivalent values', () => {
const valueTable = {
wei: '1000000000000000000',
kwei: '1000000000000000',
@ -267,8 +263,7 @@ describe('util', function () {
Object.keys(valueTable).forEach((currency) => {
const value = new ethUtil.BN(valueTable[currency], 10);
const output = util.normalizeToWei(value, currency);
assert.strictEqual(
output.toString(10),
expect(output.toString(10)).toStrictEqual(
valueTable.wei,
`value of ${output.toString(
10,
@ -278,101 +273,99 @@ describe('util', function () {
});
});
describe('#normalizeEthStringToWei', function () {
it('should convert decimal eth to pure wei BN', function () {
describe('#normalizeEthStringToWei', () => {
it('should convert decimal eth to pure wei BN', () => {
const input = '1.23456789';
const output = util.normalizeEthStringToWei(input);
assert.strictEqual(output.toString(10), '1234567890000000000');
expect(output.toString(10)).toStrictEqual('1234567890000000000');
});
it('should convert 1 to expected wei', function () {
it('should convert 1 to expected wei', () => {
const input = '1';
const output = util.normalizeEthStringToWei(input);
assert.strictEqual(output.toString(10), ethInWei);
expect(output.toString(10)).toStrictEqual(ethInWei);
});
it('should account for overflow numbers gracefully by dropping extra precision.', function () {
it('should account for overflow numbers gracefully by dropping extra precision.', () => {
const input = '1.11111111111111111111';
const output = util.normalizeEthStringToWei(input);
assert.strictEqual(output.toString(10), '1111111111111111111');
expect(output.toString(10)).toStrictEqual('1111111111111111111');
});
it('should not truncate very exact wei values that do not have extra precision.', function () {
it('should not truncate very exact wei values that do not have extra precision.', () => {
const input = '1.100000000000000001';
const output = util.normalizeEthStringToWei(input);
assert.strictEqual(output.toString(10), '1100000000000000001');
expect(output.toString(10)).toStrictEqual('1100000000000000001');
});
});
describe('#normalizeNumberToWei', function () {
it('should handle a simple use case', function () {
describe('#normalizeNumberToWei', () => {
it('should handle a simple use case', () => {
const input = 0.0002;
const output = util.normalizeNumberToWei(input, 'ether');
const str = output.toString(10);
assert.strictEqual(str, '200000000000000');
expect(str).toStrictEqual('200000000000000');
});
it('should convert a kwei number to the appropriate equivalent wei', function () {
it('should convert a kwei number to the appropriate equivalent wei', () => {
const result = util.normalizeNumberToWei(1.111, 'kwei');
assert.strictEqual(result.toString(10), '1111', 'accepts decimals');
expect(result.toString(10)).toStrictEqual('1111', 'accepts decimals');
});
it('should convert a ether number to the appropriate equivalent wei', function () {
it('should convert a ether number to the appropriate equivalent wei', () => {
const result = util.normalizeNumberToWei(1.111, 'ether');
assert.strictEqual(
result.toString(10),
'1111000000000000000',
'accepts decimals',
);
expect(result.toString(10)).toStrictEqual('1111000000000000000');
});
});
describe('#isHex', function () {
it('should return true when given a hex string', function () {
describe('#isHex', () => {
it('should return true when given a hex string', () => {
const result = util.isHex(
'c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2',
);
assert(result);
expect(result).toStrictEqual(true);
});
it('should return false when given a non-hex string', function () {
it('should return false when given a non-hex string', () => {
const result = util.isHex(
'c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714imnotreal',
);
assert(!result);
expect(result).toStrictEqual(false);
});
it('should return false when given a string containing a non letter/number character', function () {
it('should return false when given a string containing a non letter/number character', () => {
const result = util.isHex(
'c3ab8ff13720!8ad9047dd39466b3c%8974e592c2fa383d4a396071imnotreal',
);
assert(!result);
expect(result).toStrictEqual(false);
});
it('should return true when given a hex string with hex-prefix', function () {
it('should return true when given a hex string with hex-prefix', () => {
const result = util.isHex(
'0xc3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2',
);
assert(result);
expect(result).toStrictEqual(true);
});
});
describe('#getRandomFileName', function () {
it('should only return a string containing alphanumeric characters', function () {
describe('#getRandomFileName', () => {
it('should only return a string containing alphanumeric characters', () => {
const result = util.getRandomFileName();
assert(result.match(/^[a-zA-Z0-9]*$/gu));
expect(result[0]).toStrictEqual(
expect.stringMatching(/^[a-zA-Z0-9]*$/gu),
);
});
// 50 samples
it('should return a string that is between 6 and 12 characters in length', function () {
it('should return a string that is between 6 and 12 characters in length', () => {
for (let i = 0; i < 50; i++) {
const result = util.getRandomFileName();
assert(result.length >= 6 && result.length <= 12);
expect(result.length >= 6 && result.length <= 12).toStrictEqual(true);
}
});
});
});
describe('checkExistingAddresses', function () {
describe('checkExistingAddresses', () => {
const tokenList = [
{ address: 'A' },
{ address: 'n' },
@ -380,28 +373,28 @@ describe('util', function () {
{ address: 'z' },
];
it('should return true when a lowercase address matches an uppercase address in the passed list', function () {
assert(util.checkExistingAddresses('q', tokenList) === true);
it('should return true when a lowercase address matches an uppercase address in the passed list', () => {
expect(util.checkExistingAddresses('q', tokenList)).toStrictEqual(true);
});
it('should return true when an uppercase address matches a lowercase address in the passed list', function () {
assert(util.checkExistingAddresses('N', tokenList) === true);
it('should return true when an uppercase address matches a lowercase address in the passed list', () => {
expect(util.checkExistingAddresses('N', tokenList)).toStrictEqual(true);
});
it('should return true when a lowercase address matches a lowercase address in the passed list', function () {
assert(util.checkExistingAddresses('z', tokenList) === true);
it('should return true when a lowercase address matches a lowercase address in the passed list', () => {
expect(util.checkExistingAddresses('z', tokenList)).toStrictEqual(true);
});
it('should return true when an uppercase address matches an uppercase address in the passed list', function () {
assert(util.checkExistingAddresses('Q', tokenList) === true);
it('should return true when an uppercase address matches an uppercase address in the passed list', () => {
expect(util.checkExistingAddresses('Q', tokenList)).toStrictEqual(true);
});
it('should return false when the passed address is not in the passed list', function () {
assert(util.checkExistingAddresses('b', tokenList) === false);
it('should return false when the passed address is not in the passed list', () => {
expect(util.checkExistingAddresses('b', tokenList)).toStrictEqual(false);
});
});
describe('toPrecisionWithoutTrailingZeros', function () {
describe('toPrecisionWithoutTrailingZeros', () => {
const testData = [
{ args: ['0', 9], result: '0' },
{ args: [0, 9], result: '0' },
@ -439,29 +432,27 @@ describe('util', function () {
];
testData.forEach(({ args, result }) => {
it(`should return ${result} when passed number ${args[0]} and precision ${args[1]}`, function () {
assert.strictEqual(
util.toPrecisionWithoutTrailingZeros(...args),
it(`should return ${result} when passed number ${args[0]} and precision ${args[1]}`, () => {
expect(util.toPrecisionWithoutTrailingZeros(...args)).toStrictEqual(
result,
);
});
});
});
describe('addHexPrefixToObjectValues()', function () {
it('should return a new object with the same properties with a 0x prefix', function () {
assert.deepStrictEqual(
describe('addHexPrefixToObjectValues()', () => {
it('should return a new object with the same properties with a 0x prefix', () => {
expect(
util.addHexPrefixToObjectValues({
prop1: '0x123',
prop2: '456',
prop3: 'x',
}),
{
prop1: '0x123',
prop2: '0x456',
prop3: '0xx',
},
);
).toStrictEqual({
prop1: '0x123',
prop2: '0x456',
prop3: '0xx',
});
});
});
});

View File

@ -1,4 +1,3 @@
import assert from 'assert';
import * as reactRedux from 'react-redux';
import { renderHook } from '@testing-library/react-hooks';
import sinon from 'sinon';
@ -13,7 +12,7 @@ describe('useCancelTransaction', function () {
let useSelector;
const dispatch = sinon.spy();
before(function () {
beforeAll(function () {
sinon.stub(reactRedux, 'useDispatch').returns(dispatch);
});
@ -21,8 +20,12 @@ describe('useCancelTransaction', function () {
dispatch.resetHistory();
});
afterAll(function () {
sinon.restore();
});
describe('when account has insufficient balance to cover gas', function () {
before(function () {
beforeAll(function () {
useSelector = sinon.stub(reactRedux, 'useSelector');
useSelector.callsFake((selector) => {
if (selector === getConversionRate) {
@ -35,6 +38,9 @@ describe('useCancelTransaction', function () {
return undefined;
});
});
afterAll(function () {
useSelector.restore();
});
transactions.forEach((transactionGroup) => {
const originalGasPrice =
transactionGroup.primaryTransaction.txParams?.gasPrice;
@ -45,13 +51,13 @@ describe('useCancelTransaction', function () {
const { result } = renderHook(() =>
useCancelTransaction(transactionGroup),
);
assert.strictEqual(result.current[0], false);
expect(result.current[0]).toStrictEqual(false);
});
it(`should return a function that opens the gas sidebar onsubmit kicks off cancellation for id ${transactionId}`, function () {
const { result } = renderHook(() =>
useCancelTransaction(transactionGroup),
);
assert.strictEqual(typeof result.current[1], 'function');
expect(typeof result.current[1]).toStrictEqual('function');
result.current[1]({
preventDefault: () => undefined,
stopPropagation: () => undefined,
@ -60,16 +66,14 @@ describe('useCancelTransaction', function () {
// calls customize-gas sidebar
// also check type= customize-gas
assert.strictEqual(
dispatchAction[dispatchAction.length - 1][0].type,
expect(dispatchAction[dispatchAction.length - 1][0].type).toStrictEqual(
actionConstants.SIDEBAR_OPEN,
);
assert.strictEqual(
expect(
dispatchAction[dispatchAction.length - 1][0].value.props.transaction
.id,
transactionId,
);
).toStrictEqual(transactionId);
// call onSubmit myself
dispatchAction[dispatchAction.length - 1][0].value.props.onSubmit(
@ -77,7 +81,7 @@ describe('useCancelTransaction', function () {
'0x1',
);
assert.strictEqual(
expect(
dispatch.calledWith(
showModal({
name: 'CANCEL_TRANSACTION',
@ -87,17 +91,13 @@ describe('useCancelTransaction', function () {
gasLimit: '0x5208',
}),
),
true,
);
).toStrictEqual(true);
});
});
after(function () {
useSelector.restore();
});
});
describe('when account has sufficient balance to cover gas', function () {
before(function () {
beforeAll(function () {
useSelector = sinon.stub(reactRedux, 'useSelector');
useSelector.callsFake((selector) => {
if (selector === getConversionRate) {
@ -110,6 +110,11 @@ describe('useCancelTransaction', function () {
return undefined;
});
});
afterAll(function () {
useSelector.restore();
});
transactions.forEach((transactionGroup) => {
const originalGasPrice =
transactionGroup.primaryTransaction.txParams?.gasPrice;
@ -120,35 +125,33 @@ describe('useCancelTransaction', function () {
const { result } = renderHook(() =>
useCancelTransaction(transactionGroup),
);
assert.strictEqual(result.current[0], true);
expect(result.current[0]).toStrictEqual(true);
});
it(`should return a function that opens the gas sidebar onsubmit kicks off cancellation for id ${transactionId}`, function () {
const { result } = renderHook(() =>
useCancelTransaction(transactionGroup),
);
assert.strictEqual(typeof result.current[1], 'function');
expect(typeof result.current[1]).toStrictEqual('function');
result.current[1]({
preventDefault: () => undefined,
stopPropagation: () => undefined,
});
const dispatchAction = dispatch.args;
assert.strictEqual(
dispatchAction[dispatchAction.length - 1][0].type,
expect(dispatchAction[dispatchAction.length - 1][0].type).toStrictEqual(
actionConstants.SIDEBAR_OPEN,
);
assert.strictEqual(
expect(
dispatchAction[dispatchAction.length - 1][0].value.props.transaction
.id,
transactionId,
);
).toStrictEqual(transactionId);
dispatchAction[dispatchAction.length - 1][0].value.props.onSubmit(
'0x5208',
'0x1',
);
assert.strictEqual(
expect(
dispatch.calledWith(
showModal({
name: 'CANCEL_TRANSACTION',
@ -158,16 +161,8 @@ describe('useCancelTransaction', function () {
gasLimit: '0x5208',
}),
),
true,
);
).toStrictEqual(true);
});
});
after(function () {
useSelector.restore();
});
});
after(function () {
sinon.restore();
});
});

View File

@ -1,4 +1,3 @@
import assert from 'assert';
import { renderHook } from '@testing-library/react-hooks';
import * as reactRedux from 'react-redux';
import sinon from 'sinon';
@ -99,9 +98,9 @@ const tests = [
},
];
describe('useCurrencyDisplay', function () {
describe('useCurrencyDisplay', () => {
tests.forEach(({ input: { value, ...restProps }, result }) => {
describe(`when input is { value: ${value}, decimals: ${restProps.numberOfDecimals}, denomation: ${restProps.denomination} }`, function () {
describe(`when input is { value: ${value}, decimals: ${restProps.numberOfDecimals}, denomation: ${restProps.denomination} }`, () => {
const stub = sinon.stub(reactRedux, 'useSelector');
stub.callsFake((selector) => {
if (selector === getCurrentCurrency) {
@ -116,14 +115,14 @@ describe('useCurrencyDisplay', function () {
const hookReturn = renderHook(() => useCurrencyDisplay(value, restProps));
const [displayValue, parts] = hookReturn.result.current;
stub.restore();
it(`should return ${result.displayValue} as displayValue`, function () {
assert.strictEqual(displayValue, result.displayValue);
it(`should return ${result.displayValue} as displayValue`, () => {
expect(displayValue).toStrictEqual(result.displayValue);
});
it(`should return ${result.value} as value`, function () {
assert.strictEqual(parts.value, result.value);
it(`should return ${result.value} as value`, () => {
expect(parts.value).toStrictEqual(result.value);
});
it(`should return ${result.suffix} as suffix`, function () {
assert.strictEqual(parts.suffix, result.suffix);
it(`should return ${result.suffix} as suffix`, () => {
expect(parts.suffix).toStrictEqual(result.suffix);
});
});
});

View File

@ -1,4 +1,3 @@
import assert from 'assert';
import * as reactRedux from 'react-redux';
import { renderHook } from '@testing-library/react-hooks';
import sinon from 'sinon';
@ -8,8 +7,8 @@ import * as methodDataHook from './useMethodData';
import * as metricEventHook from './useMetricEvent';
import { useRetryTransaction } from './useRetryTransaction';
describe('useRetryTransaction', function () {
describe('when transaction meets retry enabled criteria', function () {
describe('useRetryTransaction', () => {
describe('when transaction meets retry enabled criteria', () => {
const dispatch = sinon.spy(() => Promise.resolve({ blockTime: 0 }));
const trackEvent = sinon.spy();
const event = {
@ -17,16 +16,21 @@ describe('useRetryTransaction', function () {
stopPropagation: () => undefined,
};
before(function () {
beforeAll(() => {
sinon.stub(reactRedux, 'useDispatch').returns(dispatch);
sinon.stub(methodDataHook, 'useMethodData').returns({});
sinon.stub(metricEventHook, 'useMetricEvent').returns(trackEvent);
});
afterEach(function () {
afterEach(() => {
dispatch.resetHistory();
trackEvent.resetHistory();
});
afterAll(() => {
sinon.restore();
});
const retryEnabledTransaction = {
...transactions[0],
transactions: [
@ -37,22 +41,22 @@ describe('useRetryTransaction', function () {
hasRetried: false,
};
it('retryTransaction function should track metrics', function () {
it('retryTransaction function should track metrics', () => {
const { result } = renderHook(() =>
useRetryTransaction(retryEnabledTransaction, true),
);
const retry = result.current;
retry(event);
assert.strictEqual(trackEvent.calledOnce, true);
expect(trackEvent.calledOnce).toStrictEqual(true);
});
it('retryTransaction function should show retry sidebar', async function () {
it('retryTransaction function should show retry sidebar', async () => {
const { result } = renderHook(() =>
useRetryTransaction(retryEnabledTransaction, true),
);
const retry = result.current;
await retry(event);
assert.strictEqual(
expect(
dispatch.calledWith(
showSidebar({
transitionName: 'sidebar-left',
@ -60,11 +64,10 @@ describe('useRetryTransaction', function () {
props: { transaction: retryEnabledTransaction.initialTransaction },
}),
),
true,
);
).toStrictEqual(true);
});
it('should handle cancelled or multiple speedup transactions', async function () {
it('should handle cancelled or multiple speedup transactions', async () => {
const cancelledTransaction = {
initialTransaction: {
...transactions[0].initialTransaction,
@ -96,7 +99,7 @@ describe('useRetryTransaction', function () {
);
const retry = result.current;
await retry(event);
assert.strictEqual(
expect(
dispatch.calledWith(
showSidebar({
transitionName: 'sidebar-left',
@ -104,12 +107,7 @@ describe('useRetryTransaction', function () {
props: { transaction: cancelledTransaction.primaryTransaction },
}),
),
true,
);
});
after(function () {
sinon.restore();
).toStrictEqual(true);
});
});
});

View File

@ -1,4 +1,4 @@
import assert from 'assert';
/* eslint-disable jest/no-conditional-expect */
import { ethers } from 'ethers';
import { renderHook } from '@testing-library/react-hooks';
import { TRANSACTION_TYPES } from '../../../shared/constants/transaction';
@ -44,23 +44,23 @@ const tests = [
},
];
describe('useTokenData', function () {
describe('useTokenData', () => {
tests.forEach((test) => {
const testTitle =
test.tokenData === null
? `should return null when no data provided`
: `should return properly decoded data with _value ${test.tokenData.args[1].value}`;
it(testTitle, function () {
// eslint-disable-next-line no-negated-condition
test.tokenData !== null
? `should return properly decoded data with _value ${test.tokenData.args[1]}`
: `should return null when no data provided`;
it(`${testTitle}`, () => {
const { result } = renderHook(() => useTokenData(test.data));
if (test.tokenData) {
assert.strictEqual(result.current.name, test.tokenData.name);
assert.strictEqual(
result.current.args[0].toLowerCase(),
expect(result.current.name).toStrictEqual(test.tokenData.name);
expect(result.current.args[0].toLowerCase()).toStrictEqual(
test.tokenData.args[0],
);
assert.ok(test.tokenData.args[1].eq(result.current.args[1]));
expect(test.tokenData.args[1]).toStrictEqual(result.current.args[1]);
} else {
assert.strictEqual(result.current, test.tokenData);
expect(result.current).toStrictEqual(test.tokenData);
}
});
});

View File

@ -1,4 +1,3 @@
import assert from 'assert';
import { renderHook } from '@testing-library/react-hooks';
import sinon from 'sinon';
import * as tokenUtil from '../helpers/utils/token-util';
@ -118,19 +117,21 @@ const tests = [
},
];
describe('useTokenDisplayValue', function () {
describe('useTokenDisplayValue', () => {
tests.forEach((test, idx) => {
describe(`when input is decimals: ${test.token.decimals} and value: ${test.tokenValue}`, function () {
it(`should return ${test.displayValue} as displayValue`, function () {
describe(`when input is decimals: ${test.token.decimals} and value: ${test.tokenValue}`, () => {
it(`should return ${test.displayValue} as displayValue`, () => {
const getTokenValueStub = sinon.stub(tokenUtil, 'getTokenValueParam');
const getTokenDataStub = sinon.stub(txUtil, 'getTokenData');
getTokenDataStub.callsFake(() => test.tokenData);
getTokenValueStub.callsFake(() => test.tokenValue);
const { result } = renderHook(() =>
useTokenDisplayValue(`${idx}-fakestring`, test.token),
);
sinon.restore();
assert.strictEqual(result.current, test.displayValue);
expect(result.current).toStrictEqual(test.displayValue);
});
});
});

View File

@ -1,4 +1,3 @@
import assert from 'assert';
import React from 'react';
import * as reactRedux from 'react-redux';
import { renderHook } from '@testing-library/react-hooks';
@ -133,8 +132,8 @@ const renderHookWithRouter = (cb, tokenAddress) => {
return renderHook(cb, { wrapper });
};
describe('useTransactionDisplayData', function () {
before(function () {
describe('useTransactionDisplayData', () => {
beforeAll(() => {
useSelector = sinon.stub(reactRedux, 'useSelector');
useTokenFiatAmount = sinon.stub(
useTokenFiatAmountHooks,
@ -172,92 +171,88 @@ describe('useTransactionDisplayData', function () {
return null;
});
});
afterAll(() => {
sinon.restore();
});
transactions.forEach((transactionGroup, idx) => {
describe(`when called with group containing primaryTransaction id ${transactionGroup.primaryTransaction.id}`, function () {
describe(`when called with group containing primaryTransaction id ${transactionGroup.primaryTransaction.id}`, () => {
const expected = expectedResults[idx];
const tokenAddress =
transactionGroup.primaryTransaction?.destinationTokenAddress;
it(`should return a title of ${expected.title}`, function () {
it(`should return a title of ${expected.title}`, () => {
const { result } = renderHookWithRouter(
() => useTransactionDisplayData(transactionGroup),
tokenAddress,
);
assert.strictEqual(result.current.title, expected.title);
expect(result.current.title).toStrictEqual(expected.title);
});
it(`should return a subtitle of ${expected.subtitle}`, function () {
it(`should return a subtitle of ${expected.subtitle}`, () => {
const { result } = renderHookWithRouter(
() => useTransactionDisplayData(transactionGroup),
tokenAddress,
);
assert.strictEqual(result.current.subtitle, expected.subtitle);
expect(result.current.subtitle).toStrictEqual(expected.subtitle);
});
it(`should return a category of ${expected.category}`, function () {
it(`should return a category of ${expected.category}`, () => {
const { result } = renderHookWithRouter(
() => useTransactionDisplayData(transactionGroup),
tokenAddress,
);
assert.strictEqual(result.current.category, expected.category);
expect(result.current.category).toStrictEqual(expected.category);
});
it(`should return a primaryCurrency of ${expected.primaryCurrency}`, function () {
it(`should return a primaryCurrency of ${expected.primaryCurrency}`, () => {
const { result } = renderHookWithRouter(
() => useTransactionDisplayData(transactionGroup),
tokenAddress,
);
assert.strictEqual(
result.current.primaryCurrency,
expect(result.current.primaryCurrency).toStrictEqual(
expected.primaryCurrency,
);
});
it(`should return a secondaryCurrency of ${expected.secondaryCurrency}`, function () {
it(`should return a secondaryCurrency of ${expected.secondaryCurrency}`, () => {
const { result } = renderHookWithRouter(
() => useTransactionDisplayData(transactionGroup),
tokenAddress,
);
assert.strictEqual(
result.current.secondaryCurrency,
expect(result.current.secondaryCurrency).toStrictEqual(
expected.secondaryCurrency,
);
});
it(`should return a displayedStatusKey of ${expected.displayedStatusKey}`, function () {
it(`should return a displayedStatusKey of ${expected.displayedStatusKey}`, () => {
const { result } = renderHookWithRouter(
() => useTransactionDisplayData(transactionGroup),
tokenAddress,
);
assert.strictEqual(
result.current.displayedStatusKey,
expect(result.current.displayedStatusKey).toStrictEqual(
expected.displayedStatusKey,
);
});
it(`should return a recipientAddress of ${expected.recipientAddress}`, function () {
it(`should return a recipientAddress of ${expected.recipientAddress}`, () => {
const { result } = renderHookWithRouter(
() => useTransactionDisplayData(transactionGroup),
tokenAddress,
);
assert.strictEqual(
result.current.recipientAddress,
expect(result.current.recipientAddress).toStrictEqual(
expected.recipientAddress,
);
});
it(`should return a senderAddress of ${expected.senderAddress}`, function () {
it(`should return a senderAddress of ${expected.senderAddress}`, () => {
const { result } = renderHookWithRouter(
() => useTransactionDisplayData(transactionGroup),
tokenAddress,
);
assert.strictEqual(
result.current.senderAddress,
expect(result.current.senderAddress).toStrictEqual(
expected.senderAddress,
);
});
});
});
it('should return an appropriate object', function () {
it('should return an appropriate object', () => {
const { result } = renderHookWithRouter(() =>
useTransactionDisplayData(transactions[0]),
);
assert.deepStrictEqual(result.current, expectedResults[0]);
});
after(function () {
useSelector.restore();
useI18nContext.restore();
expect(result.current).toStrictEqual(expectedResults[0]);
});
});

View File

@ -1,4 +1,3 @@
import assert from 'assert';
import { renderHook } from '@testing-library/react-hooks';
import * as reactRedux from 'react-redux';
import sinon from 'sinon';
@ -122,9 +121,9 @@ function getFakeUseSelector(state) {
};
}
describe('useUserPreferencedCurrency', function () {
describe('useUserPreferencedCurrency', () => {
tests.forEach(({ params: { type, ...otherParams }, state, result }) => {
describe(`when showFiat is ${state.showFiat}, useNativeCurrencyAsPrimary is ${state.useNativeCurrencyAsPrimaryCurrency} and type is ${type}`, function () {
describe(`when showFiat is ${state.showFiat}, useNativeCurrencyAsPrimary is ${state.useNativeCurrencyAsPrimaryCurrency} and type is ${type}`, () => {
const stub = sinon.stub(reactRedux, 'useSelector');
stub.callsFake(getFakeUseSelector(state));
@ -134,14 +133,13 @@ describe('useUserPreferencedCurrency', function () {
stub.restore();
it(`should return currency as ${
result.currency || 'not modified by user preferences'
}`, function () {
assert.strictEqual(hookResult.current.currency, result.currency);
}`, () => {
expect(hookResult.current.currency).toStrictEqual(result.currency);
});
it(`should return decimals as ${
result.numberOfDecimals || 'not modified by user preferences'
}`, function () {
assert.strictEqual(
hookResult.current.numberOfDecimals,
}`, () => {
expect(hookResult.current.numberOfDecimals).toStrictEqual(
result.numberOfDecimals,
);
});

View File

@ -1,4 +1,3 @@
import assert from 'assert';
import React from 'react';
import { Provider } from 'react-redux';
import sinon from 'sinon';
@ -6,7 +5,7 @@ import configureMockStore from 'redux-mock-store';
import { mountWithRouter } from '../../../../test/lib/render-helpers';
import AddToken from './add-token.container';
describe('Add Token', function () {
describe('Add Token', () => {
let wrapper;
const state = {
@ -29,8 +28,8 @@ describe('Add Token', function () {
showSearchTab: true,
};
describe('Add Token', function () {
before(function () {
describe('Add Token', () => {
beforeAll(() => {
wrapper = mountWithRouter(
<Provider store={store}>
<AddToken.WrappedComponent {...props} />
@ -41,76 +40,72 @@ describe('Add Token', function () {
wrapper.find({ name: 'customToken' }).simulate('click');
});
afterEach(function () {
afterEach(() => {
props.history.push.reset();
});
it('next button is disabled when no fields are populated', function () {
it('next button is disabled when no fields are populated', () => {
const nextButton = wrapper.find(
'.button.btn-secondary.page-container__footer-button',
);
assert.strictEqual(nextButton.props().disabled, true);
expect(nextButton.props().disabled).toStrictEqual(true);
});
it('edits token address', function () {
it('edits token address', () => {
const tokenAddress = '0x617b3f8050a0BD94b6b1da02B4384eE5B4DF13F4';
const event = { target: { value: tokenAddress } };
const customAddress = wrapper.find('input#custom-address');
customAddress.simulate('change', event);
assert.strictEqual(
expect(
wrapper.find('AddToken').instance().state.customAddress,
tokenAddress,
);
).toStrictEqual(tokenAddress);
});
it('edits token symbol', function () {
it('edits token symbol', () => {
const tokenSymbol = 'META';
const event = { target: { value: tokenSymbol } };
const customAddress = wrapper.find('#custom-symbol');
customAddress.last().simulate('change', event);
assert.strictEqual(
expect(
wrapper.find('AddToken').instance().state.customSymbol,
tokenSymbol,
);
).toStrictEqual(tokenSymbol);
});
it('edits token decimal precision', function () {
it('edits token decimal precision', () => {
const tokenPrecision = '2';
const event = { target: { value: tokenPrecision } };
const customAddress = wrapper.find('#custom-decimals');
customAddress.last().simulate('change', event);
assert.strictEqual(
expect(
wrapper.find('AddToken').instance().state.customDecimals,
tokenPrecision,
);
).toStrictEqual(tokenPrecision);
});
it('next', function () {
it('next', () => {
const nextButton = wrapper.find(
'.button.btn-secondary.page-container__footer-button',
);
nextButton.simulate('click');
assert(props.setPendingTokens.calledOnce);
assert(props.history.push.calledOnce);
assert.strictEqual(
props.history.push.getCall(0).args[0],
expect(props.setPendingTokens.calledOnce).toStrictEqual(true);
expect(props.history.push.calledOnce).toStrictEqual(true);
expect(props.history.push.getCall(0).args[0]).toStrictEqual(
'/confirm-add-token',
);
});
it('cancels', function () {
it('cancels', () => {
const cancelButton = wrapper.find(
'button.btn-default.page-container__footer-button',
);
cancelButton.simulate('click');
assert(props.clearPendingTokens.calledOnce);
assert.strictEqual(props.history.push.getCall(0).args[0], '/');
expect(props.clearPendingTokens.calledOnce).toStrictEqual(true);
expect(props.history.push.getCall(0).args[0]).toStrictEqual('/');
});
});
});

View File

@ -1,15 +1,13 @@
import assert from 'assert';
import { getMethodName } from './confirm-transaction-base.component';
describe('ConfirmTransactionBase Component', function () {
describe('getMethodName', function () {
it('should get correct method names', function () {
assert.strictEqual(getMethodName(undefined), '');
assert.strictEqual(getMethodName({}), '');
assert.strictEqual(getMethodName('confirm'), 'confirm');
assert.strictEqual(getMethodName('balanceOf'), 'balance Of');
assert.strictEqual(
getMethodName('ethToTokenSwapInput'),
describe('ConfirmTransactionBase Component', () => {
describe('getMethodName', () => {
it('should get correct method names', () => {
expect(getMethodName(undefined)).toStrictEqual('');
expect(getMethodName({})).toStrictEqual('');
expect(getMethodName('confirm')).toStrictEqual('confirm');
expect(getMethodName('balanceOf')).toStrictEqual('balance Of');
expect(getMethodName('ethToTokenSwapInput')).toStrictEqual(
'eth To Token Swap Input',
);
});

View File

@ -1,10 +1,9 @@
import assert from 'assert';
import React from 'react';
import sinon from 'sinon';
import { mountWithRouter } from '../../../../test/lib/render-helpers';
import CreateAccountPage from '.';
describe('Create Account Page', function () {
describe('Create Account Page', () => {
let wrapper;
const props = {
@ -16,34 +15,32 @@ describe('Create Account Page', function () {
},
};
before(function () {
beforeAll(() => {
wrapper = mountWithRouter(<CreateAccountPage {...props} />);
});
afterEach(function () {
afterEach(() => {
props.history.push.resetHistory();
});
it('clicks create account and routes to new-account path', function () {
it('clicks create account and routes to new-account path', () => {
const createAccount = wrapper.find('.new-account__tabs__tab').at(0);
createAccount.simulate('click');
assert.strictEqual(props.history.push.getCall(0).args[0], '/new-account');
expect(props.history.push.getCall(0).args[0]).toStrictEqual('/new-account');
});
it('clicks import account and routes to import new account path', function () {
it('clicks import account and routes to import new account path', () => {
const importAccount = wrapper.find('.new-account__tabs__tab').at(1);
importAccount.simulate('click');
assert.strictEqual(
props.history.push.getCall(0).args[0],
expect(props.history.push.getCall(0).args[0]).toStrictEqual(
'/new-account/import',
);
});
it('clicks connect HD Wallet and routes to connect new account path', function () {
it('clicks connect HD Wallet and routes to connect new account path', () => {
const connectHdWallet = wrapper.find('.new-account__tabs__tab').at(2);
connectHdWallet.simulate('click');
assert.strictEqual(
props.history.push.getCall(0).args[0],
expect(props.history.push.getCall(0).args[0]).toStrictEqual(
'/new-account/connect',
);
});

View File

@ -1,4 +1,3 @@
import assert from 'assert';
import React from 'react';
import { shallow } from 'enzyme';
import sinon from 'sinon';
@ -14,88 +13,87 @@ function shallowRender(props = {}, context = {}) {
});
}
describe('ImportWithSeedPhrase Component', function () {
it('should render without error', function () {
describe('ImportWithSeedPhrase Component', () => {
it('should render without error', () => {
const root = shallowRender({
onSubmit: sinon.spy(),
});
const textareaCount = root.find('.first-time-flow__textarea').length;
assert.strictEqual(textareaCount, 1, 'should render 12 seed phrases');
expect(textareaCount).toStrictEqual(1);
});
describe('parseSeedPhrase', function () {
it('should handle a regular seed phrase', function () {
describe('parseSeedPhrase', () => {
it('should handle a regular seed phrase', () => {
const root = shallowRender({
onSubmit: sinon.spy(),
});
const { parseSeedPhrase } = root.instance();
assert.deepStrictEqual(parseSeedPhrase('foo bar baz'), 'foo bar baz');
expect(parseSeedPhrase('foo bar baz')).toStrictEqual('foo bar baz');
});
it('should handle a mixed-case seed phrase', function () {
it('should handle a mixed-case seed phrase', () => {
const root = shallowRender({
onSubmit: sinon.spy(),
});
const { parseSeedPhrase } = root.instance();
assert.deepStrictEqual(parseSeedPhrase('FOO bAr baZ'), 'foo bar baz');
expect(parseSeedPhrase('FOO bAr baZ')).toStrictEqual('foo bar baz');
});
it('should handle an upper-case seed phrase', function () {
it('should handle an upper-case seed phrase', () => {
const root = shallowRender({
onSubmit: sinon.spy(),
});
const { parseSeedPhrase } = root.instance();
assert.deepStrictEqual(parseSeedPhrase('FOO BAR BAZ'), 'foo bar baz');
expect(parseSeedPhrase('FOO BAR BAZ')).toStrictEqual('foo bar baz');
});
it('should trim extraneous whitespace from the given seed phrase', function () {
it('should trim extraneous whitespace from the given seed phrase', () => {
const root = shallowRender({
onSubmit: sinon.spy(),
});
const { parseSeedPhrase } = root.instance();
assert.deepStrictEqual(
parseSeedPhrase(' foo bar baz '),
expect(parseSeedPhrase(' foo bar baz ')).toStrictEqual(
'foo bar baz',
);
});
it('should return an empty string when given a whitespace-only string', function () {
it('should return an empty string when given a whitespace-only string', () => {
const root = shallowRender({
onSubmit: sinon.spy(),
});
const { parseSeedPhrase } = root.instance();
assert.deepStrictEqual(parseSeedPhrase(' '), '');
expect(parseSeedPhrase(' ')).toStrictEqual('');
});
it('should return an empty string when given a string with only symbols', function () {
it('should return an empty string when given a string with only symbols', () => {
const root = shallowRender({
onSubmit: sinon.spy(),
});
const { parseSeedPhrase } = root.instance();
assert.deepStrictEqual(parseSeedPhrase('$'), '');
expect(parseSeedPhrase('$')).toStrictEqual('');
});
it('should return an empty string for both null and undefined', function () {
it('should return an empty string for both null and undefined', () => {
const root = shallowRender({
onSubmit: sinon.spy(),
});
const { parseSeedPhrase } = root.instance();
assert.deepStrictEqual(parseSeedPhrase(undefined), '');
assert.deepStrictEqual(parseSeedPhrase(null), '');
expect(parseSeedPhrase(undefined)).toStrictEqual('');
expect(parseSeedPhrase(null)).toStrictEqual('');
});
});
});

View File

@ -1,37 +1,38 @@
import assert from 'assert';
import React from 'react';
import sinon from 'sinon';
import { tick } from '../../../../../test/lib/tick';
import { mountWithRouter } from '../../../../../test/lib/render-helpers';
import { DEFAULT_ROUTE } from '../../../helpers/constants/routes';
import EndOfFlowScreen from './end-of-flow.container';
describe('End of Flow Screen', function () {
describe('End of Flow Screen', () => {
let wrapper;
const props = {
history: {
push: sinon.spy(),
push: sinon.stub(),
},
setCompletedOnboarding: sinon.spy(),
setCompletedOnboarding: sinon.stub().resolves(),
};
beforeEach(function () {
beforeEach(() => {
wrapper = mountWithRouter(<EndOfFlowScreen.WrappedComponent {...props} />);
});
it('renders', function () {
assert.strictEqual(wrapper.length, 1);
it('renders', () => {
expect(wrapper).toHaveLength(1);
});
it('should navigate to the default route on click', function (done) {
it('should navigate to the default route on click', async () => {
const endOfFlowButton = wrapper.find(
'.btn-primary.first-time-flow__button',
);
endOfFlowButton.simulate('click');
setImmediate(() => {
assert(props.history.push.calledOnceWithExactly(DEFAULT_ROUTE));
done();
});
await tick();
expect(
props.history.push.calledOnceWithExactly(DEFAULT_ROUTE),
).toStrictEqual(true);
});
});

View File

@ -1,4 +1,3 @@
import assert from 'assert';
import React from 'react';
import { mountWithRouter } from '../../../../../test/lib/render-helpers';
import {
@ -10,8 +9,8 @@ import {
} from '../../../helpers/constants/routes';
import FirstTimeFlowSwitch from './first-time-flow-switch.container';
describe('FirstTimeFlowSwitch', function () {
it('redirects to /welcome route with null props', function () {
describe('FirstTimeFlowSwitch', () => {
it('redirects to /welcome route with null props', () => {
const props = {
completedOnboarding: null,
isInitialized: null,
@ -21,15 +20,14 @@ describe('FirstTimeFlowSwitch', function () {
const wrapper = mountWithRouter(
<FirstTimeFlowSwitch.WrappedComponent {...props} />,
);
assert.strictEqual(
expect(
wrapper
.find('Lifecycle')
.find({ to: { pathname: INITIALIZE_WELCOME_ROUTE } }).length,
1,
);
.find({ to: { pathname: INITIALIZE_WELCOME_ROUTE } }),
).toHaveLength(1);
});
it('redirects to / route when completedOnboarding is true', function () {
it('redirects to / route when completedOnboarding is true', () => {
const props = {
completedOnboarding: true,
};
@ -37,14 +35,12 @@ describe('FirstTimeFlowSwitch', function () {
<FirstTimeFlowSwitch.WrappedComponent {...props} />,
);
assert.strictEqual(
wrapper.find('Lifecycle').find({ to: { pathname: DEFAULT_ROUTE } })
.length,
1,
);
expect(
wrapper.find('Lifecycle').find({ to: { pathname: DEFAULT_ROUTE } }),
).toHaveLength(1);
});
it('redirects to end of flow route when seedPhraseBackedUp is true', function () {
it('redirects to end of flow route when seedPhraseBackedUp is true', () => {
const props = {
completedOnboarding: false,
seedPhraseBackedUp: true,
@ -53,15 +49,14 @@ describe('FirstTimeFlowSwitch', function () {
<FirstTimeFlowSwitch.WrappedComponent {...props} />,
);
assert.strictEqual(
expect(
wrapper
.find('Lifecycle')
.find({ to: { pathname: INITIALIZE_END_OF_FLOW_ROUTE } }).length,
1,
);
.find({ to: { pathname: INITIALIZE_END_OF_FLOW_ROUTE } }),
).toHaveLength(1);
});
it('redirects to end of flow route when seedPhraseBackedUp is false', function () {
it('redirects to end of flow route when seedPhraseBackedUp is false', () => {
const props = {
completedOnboarding: false,
seedPhraseBackedUp: false,
@ -70,15 +65,14 @@ describe('FirstTimeFlowSwitch', function () {
<FirstTimeFlowSwitch.WrappedComponent {...props} />,
);
assert.strictEqual(
expect(
wrapper
.find('Lifecycle')
.find({ to: { pathname: INITIALIZE_END_OF_FLOW_ROUTE } }).length,
1,
);
.find({ to: { pathname: INITIALIZE_END_OF_FLOW_ROUTE } }),
).toHaveLength(1);
});
it('redirects to /lock route when isUnlocked is true ', function () {
it('redirects to /lock route when isUnlocked is true', () => {
const props = {
completedOnboarding: false,
isUnlocked: true,
@ -89,13 +83,12 @@ describe('FirstTimeFlowSwitch', function () {
<FirstTimeFlowSwitch.WrappedComponent {...props} />,
);
assert.strictEqual(
wrapper.find('Lifecycle').find({ to: { pathname: LOCK_ROUTE } }).length,
1,
);
expect(
wrapper.find('Lifecycle').find({ to: { pathname: LOCK_ROUTE } }),
).toHaveLength(1);
});
it('redirects to /welcome route when isInitialized is false', function () {
it('redirects to /welcome route when isInitialized is false', () => {
const props = {
completedOnboarding: false,
isUnlocked: false,
@ -107,15 +100,14 @@ describe('FirstTimeFlowSwitch', function () {
<FirstTimeFlowSwitch.WrappedComponent {...props} />,
);
assert.strictEqual(
expect(
wrapper
.find('Lifecycle')
.find({ to: { pathname: INITIALIZE_WELCOME_ROUTE } }).length,
1,
);
.find({ to: { pathname: INITIALIZE_WELCOME_ROUTE } }),
).toHaveLength(1);
});
it('redirects to /unlock route when isInitialized is true', function () {
it('redirects to /unlock route when isInitialized is true', () => {
const props = {
completedOnboarding: false,
isUnlocked: false,
@ -127,11 +119,10 @@ describe('FirstTimeFlowSwitch', function () {
<FirstTimeFlowSwitch.WrappedComponent {...props} />,
);
assert.strictEqual(
expect(
wrapper
.find('Lifecycle')
.find({ to: { pathname: INITIALIZE_UNLOCK_ROUTE } }).length,
1,
);
.find({ to: { pathname: INITIALIZE_UNLOCK_ROUTE } }),
).toHaveLength(1);
});
});

View File

@ -1,12 +1,11 @@
import assert from 'assert';
import React from 'react';
import sinon from 'sinon';
import configureMockStore from 'redux-mock-store';
import { mountWithRouter } from '../../../../../test/lib/render-helpers';
import MetaMetricsOptIn from './metametrics-opt-in.container';
describe('MetaMetricsOptIn', function () {
it('opt out of MetaMetrics', function () {
describe('MetaMetricsOptIn', () => {
it('opt out of MetaMetrics', () => {
const props = {
history: {
push: sinon.spy(),
@ -26,7 +25,9 @@ describe('MetaMetricsOptIn', function () {
);
noThanksButton.simulate('click');
assert.ok(props.setParticipateInMetaMetrics.calledOnceWithExactly(false));
expect(
props.setParticipateInMetaMetrics.calledOnceWithExactly(false),
).toStrictEqual(true);
props.setParticipateInMetaMetrics.resetHistory();
});
});

View File

@ -1,4 +1,3 @@
import assert from 'assert';
import React from 'react';
import { shallow } from 'enzyme';
import sinon from 'sinon';
@ -13,20 +12,18 @@ function shallowRender(props = {}, context = {}) {
});
}
describe('ConfirmSeedPhrase Component', function () {
it('should render correctly', function () {
describe('ConfirmSeedPhrase Component', () => {
it('should render correctly', () => {
const root = shallowRender({
seedPhrase: '鼠 牛 虎 兔 龍 蛇 馬 羊 猴 雞 狗 豬',
});
assert.strictEqual(
root.find('.confirm-seed-phrase__seed-word--sorted').length,
expect(root.find('.confirm-seed-phrase__seed-word--sorted')).toHaveLength(
12,
'should render 12 seed phrases',
);
});
it('should add/remove selected on click', function () {
it('should add/remove selected on click', () => {
const metricsEventSpy = sinon.spy();
const pushSpy = sinon.spy();
const root = shallowRender(
@ -46,11 +43,7 @@ describe('ConfirmSeedPhrase Component', function () {
seeds.at(1).simulate('click');
seeds.at(2).simulate('click');
assert.deepStrictEqual(
root.state().selectedSeedIndices,
[0, 1, 2],
'should add seed phrase to selected on click',
);
expect(root.state().selectedSeedIndices).toStrictEqual([0, 1, 2]);
// Click on a selected seed to remove
root.state();
@ -60,14 +53,10 @@ describe('ConfirmSeedPhrase Component', function () {
.find('.confirm-seed-phrase__seed-word--sorted')
.at(1)
.simulate('click');
assert.deepStrictEqual(
root.state().selectedSeedIndices,
[0, 2],
'should remove seed phrase from selected when click again',
);
expect(root.state().selectedSeedIndices).toStrictEqual([0, 2]);
});
it('should render correctly on hover', function () {
it('should render correctly on hover', () => {
const metricsEventSpy = sinon.spy();
const pushSpy = sinon.spy();
const root = shallowRender(
@ -97,12 +86,12 @@ describe('ConfirmSeedPhrase Component', function () {
'.confirm-seed-phrase__selected-seed-words__pending-seed',
);
assert.strictEqual(pendingSeeds.at(0).props().seedIndex, 2);
assert.strictEqual(pendingSeeds.at(1).props().seedIndex, 0);
assert.strictEqual(pendingSeeds.at(2).props().seedIndex, 1);
expect(pendingSeeds.at(0).props().seedIndex).toStrictEqual(2);
expect(pendingSeeds.at(1).props().seedIndex).toStrictEqual(0);
expect(pendingSeeds.at(2).props().seedIndex).toStrictEqual(1);
});
it('should insert seed in place on drop', function () {
it('should insert seed in place on drop', () => {
const metricsEventSpy = sinon.spy();
const pushSpy = sinon.spy();
const root = shallowRender(
@ -129,11 +118,11 @@ describe('ConfirmSeedPhrase Component', function () {
root.update();
assert.deepStrictEqual(root.state().selectedSeedIndices, [2, 0, 1]);
assert.deepStrictEqual(root.state().pendingSeedIndices, [2, 0, 1]);
expect(root.state().selectedSeedIndices).toStrictEqual([2, 0, 1]);
expect(root.state().pendingSeedIndices).toStrictEqual([2, 0, 1]);
});
it('should submit correctly', async function () {
it('should submit correctly', async () => {
const originalSeed = [
'鼠',
'牛',
@ -177,14 +166,14 @@ describe('ConfirmSeedPhrase Component', function () {
await new Promise((resolve) => setTimeout(resolve, 100));
assert.deepStrictEqual(metricsEventSpy.args[0][0], {
expect(metricsEventSpy.args[0][0]).toStrictEqual({
eventOpts: {
category: 'Onboarding',
action: 'Seed Phrase Setup',
name: 'Verify Complete',
},
});
assert(initialize3BoxSpy.calledOnce);
assert.strictEqual(pushSpy.args[0][0], '/initialize/end-of-flow');
expect(initialize3BoxSpy.calledOnce).toStrictEqual(true);
expect(pushSpy.args[0][0]).toStrictEqual('/initialize/end-of-flow');
});
});

View File

@ -1,10 +1,9 @@
import assert from 'assert';
import React from 'react';
import sinon from 'sinon';
import { mount } from 'enzyme';
import RevealSeedPhrase from './reveal-seed-phrase.container';
describe('Reveal Seed Phrase', function () {
describe('Reveal Seed Phrase', () => {
let wrapper;
const TEST_SEED =
@ -19,7 +18,7 @@ describe('Reveal Seed Phrase', function () {
setCompletedOnboarding: sinon.spy(),
};
beforeEach(function () {
beforeEach(() => {
wrapper = mount(<RevealSeedPhrase.WrappedComponent {...props} />, {
context: {
t: (str) => str,
@ -28,22 +27,22 @@ describe('Reveal Seed Phrase', function () {
});
});
it('seed phrase', function () {
it('seed phrase', () => {
const seedPhrase = wrapper.find(
'.reveal-seed-phrase__secret-words--hidden',
);
assert.strictEqual(seedPhrase.length, 1);
assert.strictEqual(seedPhrase.text(), TEST_SEED);
expect(seedPhrase).toHaveLength(1);
expect(seedPhrase.text()).toStrictEqual(TEST_SEED);
});
it('clicks to reveal', function () {
it('clicks to reveal', () => {
const reveal = wrapper.find('.reveal-seed-phrase__secret-blocker');
assert.strictEqual(wrapper.state().isShowingSeedPhrase, false);
expect(wrapper.state().isShowingSeedPhrase).toStrictEqual(false);
reveal.simulate('click');
assert.strictEqual(wrapper.state().isShowingSeedPhrase, true);
expect(wrapper.state().isShowingSeedPhrase).toStrictEqual(true);
const showSeed = wrapper.find('.reveal-seed-phrase__secret-words');
assert.strictEqual(showSeed.length, 1);
expect(showSeed).toHaveLength(1);
});
});

View File

@ -1,10 +1,9 @@
import assert from 'assert';
import React from 'react';
import sinon from 'sinon';
import { mountWithRouter } from '../../../../../test/lib/render-helpers';
import SelectAction from './select-action.container';
describe('Selection Action', function () {
describe('Selection Action', () => {
let wrapper;
const props = {
@ -15,34 +14,38 @@ describe('Selection Action', function () {
},
};
beforeEach(function () {
beforeEach(() => {
wrapper = mountWithRouter(<SelectAction.WrappedComponent {...props} />);
});
afterEach(function () {
afterEach(() => {
props.setFirstTimeFlowType.resetHistory();
props.history.push.resetHistory();
});
it('clicks import wallet to route to import FTF', function () {
it('clicks import wallet to route to import FTF', () => {
const importWalletButton = wrapper
.find('.btn-primary.first-time-flow__button')
.at(0);
importWalletButton.simulate('click');
assert(props.setFirstTimeFlowType.calledOnce);
assert.strictEqual(props.setFirstTimeFlowType.getCall(0).args[0], 'import');
assert(props.history.push.calledOnce);
expect(props.setFirstTimeFlowType.calledOnce).toStrictEqual(true);
expect(props.setFirstTimeFlowType.getCall(0).args[0]).toStrictEqual(
'import',
);
expect(props.history.push.calledOnce).toStrictEqual(true);
});
it('clicks create wallet to route to create FTF ', function () {
it('clicks create wallet to route to create FTF', () => {
const createWalletButton = wrapper
.find('.btn-primary.first-time-flow__button')
.at(1);
createWalletButton.simulate('click');
assert(props.setFirstTimeFlowType.calledOnce);
assert.strictEqual(props.setFirstTimeFlowType.getCall(0).args[0], 'create');
assert(props.history.push.calledOnce);
expect(props.setFirstTimeFlowType.calledOnce).toStrictEqual(true);
expect(props.setFirstTimeFlowType.getCall(0).args[0]).toStrictEqual(
'create',
);
expect(props.history.push.calledOnce).toStrictEqual(true);
});
});

View File

@ -1,22 +1,21 @@
import assert from 'assert';
import React from 'react';
import sinon from 'sinon';
import configureMockStore from 'redux-mock-store';
import { mountWithRouter } from '../../../../../test/lib/render-helpers';
import Welcome from './welcome.container';
describe('Welcome', function () {
describe('Welcome', () => {
const mockStore = {
metamask: {},
};
const store = configureMockStore()(mockStore);
after(function () {
afterAll(() => {
sinon.restore();
});
it('routes to select action when participateInMetaMetrics is not initialized', function () {
it('routes to select action when participateInMetaMetrics is not initialized', () => {
const props = {
history: {
push: sinon.spy(),
@ -32,13 +31,12 @@ describe('Welcome', function () {
'.btn-primary.first-time-flow__button',
);
getStartedButton.simulate('click');
assert.strictEqual(
props.history.push.getCall(0).args[0],
expect(props.history.push.getCall(0).args[0]).toStrictEqual(
'/initialize/select-action',
);
});
it('routes to correct password when participateInMetaMetrics is initialized', function () {
it('routes to correct password when participateInMetaMetrics is initialized', () => {
const props = {
welcomeScreenSeen: true,
participateInMetaMetrics: false,
@ -56,8 +54,7 @@ describe('Welcome', function () {
'.btn-primary.first-time-flow__button',
);
getStartedButton.simulate('click');
assert.strictEqual(
props.history.push.getCall(0).args[0],
expect(props.history.push.getCall(0).args[0]).toStrictEqual(
'/initialize/create-password',
);
});

View File

@ -1,16 +1,16 @@
import assert from 'assert';
import React from 'react';
import sinon from 'sinon';
import { mount } from 'enzyme';
import RevealSeedPage from './reveal-seed';
describe('Reveal Seed Page', function () {
it('form submit', function () {
describe('Reveal Seed Page', () => {
it('form submit', () => {
const props = {
history: {
push: sinon.spy(),
},
requestRevealSeedWords: sinon.stub().resolves(),
mostRecentOverviewPage: '/',
};
const wrapper = mount(<RevealSeedPage.WrappedComponent {...props} />, {
context: {
@ -19,6 +19,6 @@ describe('Reveal Seed Page', function () {
});
wrapper.find('form').simulate('submit');
assert(props.requestRevealSeedWords.calledOnce);
expect(props.requestRevealSeedWords.calledOnce).toStrictEqual(true);
});
});

View File

@ -1,11 +1,10 @@
import assert from 'assert';
import React from 'react';
import sinon from 'sinon';
import { mountWithRouter } from '../../../../test/lib/render-helpers';
import Lock from './lock.container';
describe('Lock', function () {
it('replaces history with default route when isUnlocked false', function () {
describe('Lock', () => {
it('replaces history with default route when isUnlocked false', () => {
const props = {
isUnlocked: false,
history: {
@ -15,10 +14,10 @@ describe('Lock', function () {
mountWithRouter(<Lock.WrappedComponent {...props} />);
assert.strictEqual(props.history.replace.getCall(0).args[0], '/');
expect(props.history.replace.getCall(0).args[0]).toStrictEqual('/');
});
it('locks and pushes history with default route when isUnlocked true', function (done) {
it('locks and pushes history with default route when isUnlocked true', async () => {
const props = {
isUnlocked: true,
lockMetamask: sinon.stub(),
@ -31,10 +30,7 @@ describe('Lock', function () {
mountWithRouter(<Lock.WrappedComponent {...props} />);
assert(props.lockMetamask.calledOnce);
setImmediate(() => {
assert.strictEqual(props.history.push.getCall(0).args[0], '/');
done();
});
expect(await props.lockMetamask.calledOnce).toStrictEqual(true);
expect(props.history.push.getCall(0).args[0]).toStrictEqual('/');
});
});

Some files were not shown because too many files have changed in this diff Show More