aboutsummaryrefslogtreecommitdiffstats
path: root/test/unit
diff options
context:
space:
mode:
authorDan Finlay <542863+danfinlay@users.noreply.github.com>2018-08-08 02:31:42 +0800
committerGitHub <noreply@github.com>2018-08-08 02:31:42 +0800
commit0601df9dae488d997277bb6b52c28df27546e27c (patch)
treeae33a0c4610b9a9e865c797258232542a72f57b6 /test/unit
parent4598554fea7b9435e5cbecc4735c479ffbadf37e (diff)
parentf6490a2a6eda943a374c01df5884acb07ba28869 (diff)
downloadtangerine-wallet-browser-0601df9dae488d997277bb6b52c28df27546e27c.tar
tangerine-wallet-browser-0601df9dae488d997277bb6b52c28df27546e27c.tar.gz
tangerine-wallet-browser-0601df9dae488d997277bb6b52c28df27546e27c.tar.bz2
tangerine-wallet-browser-0601df9dae488d997277bb6b52c28df27546e27c.tar.lz
tangerine-wallet-browser-0601df9dae488d997277bb6b52c28df27546e27c.tar.xz
tangerine-wallet-browser-0601df9dae488d997277bb6b52c28df27546e27c.tar.zst
tangerine-wallet-browser-0601df9dae488d997277bb6b52c28df27546e27c.zip
Merge pull request #4954 from MetaMask/v4.9.0
V4.9.0
Diffstat (limited to 'test/unit')
-rw-r--r--test/unit/actions/tx_test.js102
-rw-r--r--test/unit/app/account-import-strategies.spec.js3
-rw-r--r--test/unit/app/controllers/address-book-controller.js2
-rw-r--r--test/unit/app/controllers/detect-tokens-test.js141
-rw-r--r--test/unit/app/controllers/metamask-controller-test.js156
-rw-r--r--test/unit/app/controllers/network-contoller-test.js3
-rw-r--r--test/unit/app/controllers/preferences-controller-test.js25
-rw-r--r--test/unit/app/controllers/transactions/nonce-tracker-test.js14
-rw-r--r--test/unit/app/controllers/transactions/pending-tx-test.js57
-rw-r--r--test/unit/app/controllers/transactions/recipient-blacklist-checker-test.js6
-rw-r--r--test/unit/app/controllers/transactions/tx-controller-test.js21
-rw-r--r--test/unit/app/controllers/transactions/tx-gas-util-test.js1
-rw-r--r--test/unit/app/controllers/transactions/tx-state-history-helper-test.js41
-rw-r--r--test/unit/app/controllers/transactions/tx-state-manager-test.js72
-rw-r--r--test/unit/app/controllers/transactions/tx-utils-test.js4
-rw-r--r--test/unit/app/edge-encryptor-test.js10
-rw-r--r--test/unit/app/nodeify-test.js8
-rw-r--r--test/unit/app/pending-balance-test.js7
-rw-r--r--test/unit/app/seed-phrase-verifier-test.js93
-rw-r--r--test/unit/app/util-test.js2
-rw-r--r--test/unit/components/balance-component-test.js2
-rw-r--r--test/unit/components/bn-as-decimal-input-test.js4
-rw-r--r--test/unit/components/pending-tx-test.js67
-rw-r--r--test/unit/migrations/022-test.js16
-rw-r--r--test/unit/migrations/023-test.js12
-rw-r--r--test/unit/migrations/024-test.js11
-rw-r--r--test/unit/migrations/025-test.js10
-rw-r--r--test/unit/migrations/027-test.js50
-rw-r--r--test/unit/migrations/template-test.js1
-rw-r--r--test/unit/responsive/components/dropdown-test.js58
30 files changed, 637 insertions, 362 deletions
diff --git a/test/unit/actions/tx_test.js b/test/unit/actions/tx_test.js
index c110f71fc..160cd4552 100644
--- a/test/unit/actions/tx_test.js
+++ b/test/unit/actions/tx_test.js
@@ -1,74 +1,54 @@
-// var jsdom = require('mocha-jsdom')
var assert = require('assert')
-var freeze = require('deep-freeze-strict')
var path = require('path')
-var sinon = require('sinon')
-var actions = require(path.join(__dirname, '..', '..', '..', 'ui', 'app', 'actions.js'))
-var reducers = require(path.join(__dirname, '..', '..', '..', 'ui', 'app', 'reducers.js'))
+import configureMockStore from 'redux-mock-store'
+import thunk from 'redux-thunk'
-describe('tx confirmation screen', function () {
- beforeEach(function () {
- this.sinon = sinon.createSandbox()
- })
-
- afterEach(function () {
- this.sinon.restore()
- })
+const actions = require(path.join(__dirname, '../../../ui/app/actions.js'))
- var initialState, result
+const middlewares = [thunk]
+const mockStore = configureMockStore(middlewares)
- describe('when there is only one tx', function () {
- var firstTxId = 1457634084250832
-
- beforeEach(function () {
- initialState = {
- appState: {
- currentView: {
- name: 'confTx',
- },
- },
- metamask: {
- unapprovedTxs: {
- '1457634084250832': {
- id: 1457634084250832,
- status: 'unconfirmed',
- time: 1457634084250,
- },
- },
+describe('tx confirmation screen', function () {
+ const txId = 1457634084250832
+ const initialState = {
+ appState: {
+ currentView: {
+ name: 'confTx',
+ },
+ },
+ metamask: {
+ unapprovedTxs: {
+ [txId]: {
+ id: txId,
+ status: 'unconfirmed',
+ time: 1457634084250,
},
- }
- freeze(initialState)
+ },
+ },
+ }
+
+ const store = mockStore(initialState)
+
+ describe('cancelTx', function () {
+ before(function (done) {
+ actions._setBackgroundConnection({
+ approveTransaction (txId, cb) { cb('An error!') },
+ cancelTransaction (txId, cb) { cb() },
+ clearSeedWordCache (cb) { cb() },
+ getState (cb) { cb() },
+ })
+ done()
})
- describe('cancelTx', function () {
- before(function (done) {
- actions._setBackgroundConnection({
- approveTransaction (txId, cb) { cb('An error!') },
- cancelTransaction (txId, cb) { cb() },
- clearSeedWordCache (cb) { cb() },
+ it('creates COMPLETED_TX with the cancelled transaction ID', function (done) {
+ store.dispatch(actions.cancelTx({ id: txId }))
+ .then(() => {
+ const storeActions = store.getActions()
+ const completedTxAction = storeActions.find(({ type }) => type === actions.COMPLETED_TX)
+ assert.equal(completedTxAction.value, txId)
+ done()
})
-
- actions.cancelTx({value: firstTxId})((action) => {
- result = reducers(initialState, action)
- })
- done()
- })
-
- it('should transition to the account detail view', function () {
- assert.equal(result.appState.currentView.name, 'accountDetail')
- })
-
- it('should have no unconfirmed txs remaining', function () {
- var count = getUnconfirmedTxCount(result)
- assert.equal(count, 0)
- })
})
})
})
-
-function getUnconfirmedTxCount (state) {
- var txs = state.metamask.unapprovedTxs
- var count = Object.keys(txs).length
- return count
-}
diff --git a/test/unit/app/account-import-strategies.spec.js b/test/unit/app/account-import-strategies.spec.js
index 216c2f698..d20ba0f0b 100644
--- a/test/unit/app/account-import-strategies.spec.js
+++ b/test/unit/app/account-import-strategies.spec.js
@@ -1,5 +1,4 @@
const assert = require('assert')
-const path = require('path')
const ethUtil = require('ethereumjs-util')
const accountImporter = require('../../../app/scripts/account-import-strategies/index')
const { assertRejects } = require('../test-utils')
@@ -15,7 +14,7 @@ describe('Account Import Strategies', function () {
})
it('throws an error for empty string private key', async () => {
- assertRejects(async function() {
+ assertRejects(async function () {
await accountImporter.importAccount('Private Key', [ '' ])
}, Error, 'no empty strings')
})
diff --git a/test/unit/app/controllers/address-book-controller.js b/test/unit/app/controllers/address-book-controller.js
index dc4b8e3ff..1350e1a61 100644
--- a/test/unit/app/controllers/address-book-controller.js
+++ b/test/unit/app/controllers/address-book-controller.js
@@ -12,7 +12,7 @@ const stubPreferencesStore = {
},
}
},
-};
+}
describe('address-book-controller', function () {
var addressBookController
diff --git a/test/unit/app/controllers/detect-tokens-test.js b/test/unit/app/controllers/detect-tokens-test.js
new file mode 100644
index 000000000..426ffe23a
--- /dev/null
+++ b/test/unit/app/controllers/detect-tokens-test.js
@@ -0,0 +1,141 @@
+const assert = require('assert')
+const sinon = require('sinon')
+const ObservableStore = require('obs-store')
+const DetectTokensController = require('../../../../app/scripts/controllers/detect-tokens')
+const NetworkController = require('../../../../app/scripts/controllers/network/network')
+const PreferencesController = require('../../../../app/scripts/controllers/preferences')
+
+describe('DetectTokensController', () => {
+ const sandbox = sinon.createSandbox()
+ let clock
+ let keyringMemStore
+ before(async () => {
+ keyringMemStore = new ObservableStore({ isUnlocked: false})
+ })
+ after(() => {
+ sandbox.restore()
+ })
+
+ it('should poll on correct interval', async () => {
+ const stub = sinon.stub(global, 'setInterval')
+ new DetectTokensController({ interval: 1337 }) // eslint-disable-line no-new
+ assert.strictEqual(stub.getCall(0).args[1], 1337)
+ stub.restore()
+ })
+
+ it('should be called on every polling period', async () => {
+ clock = sandbox.useFakeTimers()
+ const network = new NetworkController()
+ network.setProviderType('mainnet')
+ const preferences = new PreferencesController()
+ const controller = new DetectTokensController({ preferences: preferences, network: network, keyringMemStore: keyringMemStore })
+ controller.isOpen = true
+ controller.isUnlocked = true
+
+ var stub = sandbox.stub(controller, 'detectNewTokens')
+
+ clock.tick(1)
+ sandbox.assert.notCalled(stub)
+ clock.tick(180000)
+ sandbox.assert.called(stub)
+ clock.tick(180000)
+ sandbox.assert.calledTwice(stub)
+ clock.tick(180000)
+ sandbox.assert.calledThrice(stub)
+ })
+
+ it('should not check tokens while in test network', async () => {
+ const network = new NetworkController()
+ network.setProviderType('rinkeby')
+ const preferences = new PreferencesController()
+ const controller = new DetectTokensController({ preferences: preferences, network: network, keyringMemStore: keyringMemStore })
+ controller.isOpen = true
+ controller.isUnlocked = true
+
+ var stub = sandbox.stub(controller, 'detectTokenBalance')
+ .withArgs('0x0D262e5dC4A06a0F1c90cE79C7a60C09DfC884E4').returns(true)
+ .withArgs('0xBC86727E770de68B1060C91f6BB6945c73e10388').returns(true)
+
+ await controller.detectNewTokens()
+ sandbox.assert.notCalled(stub)
+ })
+
+ it('should only check and add tokens while in main network', async () => {
+ const network = new NetworkController()
+ network.setProviderType('mainnet')
+ const preferences = new PreferencesController()
+ const controller = new DetectTokensController({ preferences: preferences, network: network, keyringMemStore: keyringMemStore })
+ controller.isOpen = true
+ controller.isUnlocked = true
+
+ sandbox.stub(controller, 'detectTokenBalance')
+ .withArgs('0x0D262e5dC4A06a0F1c90cE79C7a60C09DfC884E4')
+ .returns(preferences.addToken('0x0d262e5dc4a06a0f1c90ce79c7a60c09dfc884e4', 'J8T', 8))
+ .withArgs('0xBC86727E770de68B1060C91f6BB6945c73e10388')
+ .returns(preferences.addToken('0xbc86727e770de68b1060c91f6bb6945c73e10388', 'XNK', 18))
+
+ await controller.detectNewTokens()
+ assert.deepEqual(preferences.store.getState().tokens, [{address: '0x0d262e5dc4a06a0f1c90ce79c7a60c09dfc884e4', decimals: 8, symbol: 'J8T'},
+ {address: '0xbc86727e770de68b1060c91f6bb6945c73e10388', decimals: 18, symbol: 'XNK'}])
+ })
+
+ it('should not detect same token while in main network', async () => {
+ const network = new NetworkController()
+ network.setProviderType('mainnet')
+ const preferences = new PreferencesController()
+ preferences.addToken('0x0d262e5dc4a06a0f1c90ce79c7a60c09dfc884e4', 'J8T', 8)
+ const controller = new DetectTokensController({ preferences: preferences, network: network, keyringMemStore: keyringMemStore })
+ controller.isOpen = true
+ controller.isUnlocked = true
+
+ sandbox.stub(controller, 'detectTokenBalance')
+ .withArgs('0x0D262e5dC4A06a0F1c90cE79C7a60C09DfC884E4')
+ .returns(preferences.addToken('0x0d262e5dc4a06a0f1c90ce79c7a60c09dfc884e4', 'J8T', 8))
+ .withArgs('0xBC86727E770de68B1060C91f6BB6945c73e10388')
+ .returns(preferences.addToken('0xbc86727e770de68b1060c91f6bb6945c73e10388', 'XNK', 18))
+
+ await controller.detectNewTokens()
+ assert.deepEqual(preferences.store.getState().tokens, [{address: '0x0d262e5dc4a06a0f1c90ce79c7a60c09dfc884e4', decimals: 8, symbol: 'J8T'},
+ {address: '0xbc86727e770de68b1060c91f6bb6945c73e10388', decimals: 18, symbol: 'XNK'}])
+ })
+
+ it('should trigger detect new tokens when change address', async () => {
+ const network = new NetworkController()
+ network.setProviderType('mainnet')
+ const preferences = new PreferencesController()
+ const controller = new DetectTokensController({ preferences: preferences, network: network, keyringMemStore: keyringMemStore })
+ controller.isOpen = true
+ controller.isUnlocked = true
+ var stub = sandbox.stub(controller, 'detectNewTokens')
+ await preferences.setSelectedAddress('0xbc86727e770de68b1060c91f6bb6945c73e10388')
+ sandbox.assert.called(stub)
+ })
+
+ it('should trigger detect new tokens when submit password', async () => {
+ const network = new NetworkController()
+ network.setProviderType('mainnet')
+ const preferences = new PreferencesController()
+ const controller = new DetectTokensController({ preferences: preferences, network: network, keyringMemStore: keyringMemStore })
+ controller.isOpen = true
+ controller.selectedAddress = '0x0'
+ var stub = sandbox.stub(controller, 'detectNewTokens')
+ await controller._keyringMemStore.updateState({ isUnlocked: true })
+ sandbox.assert.called(stub)
+ })
+
+ it('should not trigger detect new tokens when not open or not unlocked', async () => {
+ const network = new NetworkController()
+ network.setProviderType('mainnet')
+ const preferences = new PreferencesController()
+ const controller = new DetectTokensController({ preferences: preferences, network: network, keyringMemStore: keyringMemStore })
+ controller.isOpen = true
+ controller.isUnlocked = false
+ var stub = sandbox.stub(controller, 'detectTokenBalance')
+ clock.tick(180000)
+ sandbox.assert.notCalled(stub)
+ controller.isOpen = false
+ controller.isUnlocked = true
+ clock.tick(180000)
+ sandbox.assert.notCalled(stub)
+ })
+})
diff --git a/test/unit/app/controllers/metamask-controller-test.js b/test/unit/app/controllers/metamask-controller-test.js
index 0dda4609b..9164fe246 100644
--- a/test/unit/app/controllers/metamask-controller-test.js
+++ b/test/unit/app/controllers/metamask-controller-test.js
@@ -222,6 +222,129 @@ describe('MetaMaskController', function () {
})
})
+ describe('connectHardware', function () {
+
+ it('should throw if it receives an unknown device name', async function () {
+ try {
+ await metamaskController.connectHardware('Some random device name', 0)
+ } catch (e) {
+ assert.equal(e, 'Error: MetamaskController:connectHardware - Unknown device')
+ }
+ })
+
+ it('should add the Trezor Hardware keyring', async function () {
+ sinon.spy(metamaskController.keyringController, 'addNewKeyring')
+ await metamaskController.connectHardware('trezor', 0).catch((e) => null)
+ const keyrings = await metamaskController.keyringController.getKeyringsByType(
+ 'Trezor Hardware'
+ )
+ assert.equal(metamaskController.keyringController.addNewKeyring.getCall(0).args, 'Trezor Hardware')
+ assert.equal(keyrings.length, 1)
+ })
+
+ })
+
+ describe('checkHardwareStatus', function () {
+ it('should throw if it receives an unknown device name', async function () {
+ try {
+ await metamaskController.checkHardwareStatus('Some random device name')
+ } catch (e) {
+ assert.equal(e, 'Error: MetamaskController:checkHardwareStatus - Unknown device')
+ }
+ })
+
+ it('should be locked by default', async function () {
+ await metamaskController.connectHardware('trezor', 0).catch((e) => null)
+ const status = await metamaskController.checkHardwareStatus('trezor')
+ assert.equal(status, false)
+ })
+ })
+
+ describe('forgetDevice', function () {
+ it('should throw if it receives an unknown device name', async function () {
+ try {
+ await metamaskController.forgetDevice('Some random device name')
+ } catch (e) {
+ assert.equal(e, 'Error: MetamaskController:forgetDevice - Unknown device')
+ }
+ })
+
+ it('should wipe all the keyring info', async function () {
+ await metamaskController.connectHardware('trezor', 0).catch((e) => null)
+ await metamaskController.forgetDevice('trezor')
+ const keyrings = await metamaskController.keyringController.getKeyringsByType(
+ 'Trezor Hardware'
+ )
+
+ assert.deepEqual(keyrings[0].accounts, [])
+ assert.deepEqual(keyrings[0].page, 0)
+ assert.deepEqual(keyrings[0].isUnlocked(), false)
+ })
+ })
+
+ describe('unlockTrezorAccount', function () {
+ let accountToUnlock
+ let windowOpenStub
+ let addNewAccountStub
+ let getAccountsStub
+ beforeEach(async function () {
+ accountToUnlock = 10
+ windowOpenStub = sinon.stub(window, 'open')
+ windowOpenStub.returns(noop)
+
+ addNewAccountStub = sinon.stub(metamaskController.keyringController, 'addNewAccount')
+ addNewAccountStub.returns({})
+
+ getAccountsStub = sinon.stub(metamaskController.keyringController, 'getAccounts')
+ // Need to return different address to mock the behavior of
+ // adding a new account from the keyring
+ getAccountsStub.onCall(0).returns(Promise.resolve(['0x1']))
+ getAccountsStub.onCall(1).returns(Promise.resolve(['0x2']))
+ getAccountsStub.onCall(2).returns(Promise.resolve(['0x3']))
+ getAccountsStub.onCall(3).returns(Promise.resolve(['0x4']))
+ sinon.spy(metamaskController.preferencesController, 'setAddresses')
+ sinon.spy(metamaskController.preferencesController, 'setSelectedAddress')
+ sinon.spy(metamaskController.preferencesController, 'setAccountLabel')
+ await metamaskController.connectHardware('trezor', 0).catch((e) => null)
+ await metamaskController.unlockTrezorAccount(accountToUnlock).catch((e) => null)
+ })
+
+ afterEach(function () {
+ metamaskController.keyringController.addNewAccount.restore()
+ window.open.restore()
+ })
+
+ it('should set accountToUnlock in the keyring', async function () {
+ const keyrings = await metamaskController.keyringController.getKeyringsByType(
+ 'Trezor Hardware'
+ )
+ assert.equal(keyrings[0].unlockedAccount, accountToUnlock)
+ })
+
+
+ it('should call keyringController.addNewAccount', async function () {
+ assert(metamaskController.keyringController.addNewAccount.calledOnce)
+ })
+
+ it('should call keyringController.getAccounts ', async function () {
+ assert(metamaskController.keyringController.getAccounts.called)
+ })
+
+ it('should call preferencesController.setAddresses', async function () {
+ assert(metamaskController.preferencesController.setAddresses.calledOnce)
+ })
+
+ it('should call preferencesController.setSelectedAddress', async function () {
+ assert(metamaskController.preferencesController.setSelectedAddress.calledOnce)
+ })
+
+ it('should call preferencesController.setAccountLabel', async function () {
+ assert(metamaskController.preferencesController.setAccountLabel.calledOnce)
+ })
+
+
+ })
+
describe('#setCustomRpc', function () {
const customRPC = 'https://custom.rpc/'
let rpcTarget
@@ -362,6 +485,39 @@ describe('MetaMaskController', function () {
})
})
+ describe('#removeAccount', function () {
+ let ret
+ const addressToRemove = '0x1'
+
+ beforeEach(async function () {
+ sinon.stub(metamaskController.preferencesController, 'removeAddress')
+ sinon.stub(metamaskController.accountTracker, 'removeAccount')
+ sinon.stub(metamaskController.keyringController, 'removeAccount')
+
+ ret = await metamaskController.removeAccount(addressToRemove)
+
+ })
+
+ afterEach(function () {
+ metamaskController.keyringController.removeAccount.restore()
+ metamaskController.accountTracker.removeAccount.restore()
+ metamaskController.preferencesController.removeAddress.restore()
+ })
+
+ it('should call preferencesController.removeAddress', async function () {
+ assert(metamaskController.preferencesController.removeAddress.calledWith(addressToRemove))
+ })
+ it('should call accountTracker.removeAccount', async function () {
+ assert(metamaskController.accountTracker.removeAccount.calledWith(addressToRemove))
+ })
+ it('should call keyringController.removeAccount', async function () {
+ assert(metamaskController.keyringController.removeAccount.calledWith(addressToRemove))
+ })
+ it('should return address', async function () {
+ assert.equal(ret, '0x1')
+ })
+ })
+
describe('#clearSeedWordCache', function () {
it('should have set seed words', function () {
diff --git a/test/unit/app/controllers/network-contoller-test.js b/test/unit/app/controllers/network-contoller-test.js
index 789850ef3..e16fb104e 100644
--- a/test/unit/app/controllers/network-contoller-test.js
+++ b/test/unit/app/controllers/network-contoller-test.js
@@ -5,9 +5,6 @@ const {
getNetworkDisplayName,
} = require('../../../../app/scripts/controllers/network/util')
-const { createTestProviderTools } = require('../../../stub/provider')
-const providerResultStub = {}
-
describe('# Network Controller', function () {
let networkController
const noop = () => {}
diff --git a/test/unit/app/controllers/preferences-controller-test.js b/test/unit/app/controllers/preferences-controller-test.js
index e5e751b57..e055500b1 100644
--- a/test/unit/app/controllers/preferences-controller-test.js
+++ b/test/unit/app/controllers/preferences-controller-test.js
@@ -52,6 +52,31 @@ describe('preferences controller', function () {
})
})
+ describe('removeAddress', function () {
+ it('should remove an address from state', function () {
+ preferencesController.setAddresses([
+ '0xda22le',
+ '0x7e57e2',
+ ])
+
+ preferencesController.removeAddress('0xda22le')
+
+ assert.equal(preferencesController.store.getState().identities['0xda22le'], undefined)
+ })
+
+ it('should switch accounts if the selected address is removed', function () {
+ preferencesController.setAddresses([
+ '0xda22le',
+ '0x7e57e2',
+ ])
+
+ preferencesController.setSelectedAddress('0x7e57e2')
+ preferencesController.removeAddress('0x7e57e2')
+
+ assert.equal(preferencesController.getSelectedAddress(), '0xda22le')
+ })
+ })
+
describe('setAccountLabel', function () {
it('should update a label for the given account', function () {
preferencesController.setAddresses([
diff --git a/test/unit/app/controllers/transactions/nonce-tracker-test.js b/test/unit/app/controllers/transactions/nonce-tracker-test.js
index fc852458c..6c0ac759f 100644
--- a/test/unit/app/controllers/transactions/nonce-tracker-test.js
+++ b/test/unit/app/controllers/transactions/nonce-tracker-test.js
@@ -1,12 +1,10 @@
const assert = require('assert')
const NonceTracker = require('../../../../../app/scripts/controllers/transactions/nonce-tracker')
const MockTxGen = require('../../../../lib/mock-tx-gen')
-let providerResultStub = {}
+const providerResultStub = {}
describe('Nonce Tracker', function () {
- let nonceTracker, provider
- let getPendingTransactions, pendingTxs
- let getConfirmedTransactions, confirmedTxs
+ let nonceTracker, pendingTxs, confirmedTxs
describe('#getNonceLock', function () {
@@ -182,8 +180,8 @@ describe('Nonce Tracker', function () {
describe('When all three return different values', function () {
beforeEach(function () {
const txGen = new MockTxGen()
- const confirmedTxs = txGen.generate({ status: 'confirmed' }, { count: 10 })
- const pendingTxs = txGen.generate({
+ confirmedTxs = txGen.generate({ status: 'confirmed' }, { count: 10 })
+ pendingTxs = txGen.generate({
status: 'submitted',
nonce: 100,
}, { count: 1 })
@@ -202,8 +200,8 @@ describe('Nonce Tracker', function () {
describe('Faq issue 67', function () {
beforeEach(function () {
const txGen = new MockTxGen()
- const confirmedTxs = txGen.generate({ status: 'confirmed' }, { count: 64 })
- const pendingTxs = txGen.generate({
+ confirmedTxs = txGen.generate({ status: 'confirmed' }, { count: 64 })
+ pendingTxs = txGen.generate({
status: 'submitted',
}, { count: 10 })
// 0x40 is 64 in hex:
diff --git a/test/unit/app/controllers/transactions/pending-tx-test.js b/test/unit/app/controllers/transactions/pending-tx-test.js
index e7705c594..8bf2da6f8 100644
--- a/test/unit/app/controllers/transactions/pending-tx-test.js
+++ b/test/unit/app/controllers/transactions/pending-tx-test.js
@@ -1,20 +1,12 @@
const assert = require('assert')
-const ethUtil = require('ethereumjs-util')
-const EthTx = require('ethereumjs-tx')
-const ObservableStore = require('obs-store')
-const clone = require('clone')
const { createTestProviderTools } = require('../../../../stub/provider')
const PendingTransactionTracker = require('../../../../../app/scripts/controllers/transactions/pending-tx-tracker')
const MockTxGen = require('../../../../lib/mock-tx-gen')
const sinon = require('sinon')
-const noop = () => true
-const currentNetworkId = 42
-const otherNetworkId = 36
-const privKey = new Buffer('8718b9618a37d1fc78c436511fc6df3c8258d3250635bba617f33003270ec03e', 'hex')
describe('PendingTransactionTracker', function () {
- let pendingTxTracker, txMeta, txMetaNoHash, txMetaNoRawTx, providerResultStub,
+ let pendingTxTracker, txMeta, txMetaNoHash, providerResultStub,
provider, txMeta3, txList, knownErrors
this.timeout(10000)
beforeEach(function () {
@@ -34,11 +26,7 @@ describe('PendingTransactionTracker', function () {
status: 'signed',
txParams: { from: '0x1678a085c290ebd122dc42cba69373b5953b831d'},
}
- txMetaNoRawTx = {
- hash: '0x0593ee121b92e10d63150ad08b4b8f9c7857d1bd160195ee648fb9a0f8d00eeb',
- status: 'signed',
- txParams: { from: '0x1678a085c290ebd122dc42cba69373b5953b831d'},
- }
+
providerResultStub = {}
provider = createTestProviderTools({ scaffold: providerResultStub }).provider
@@ -47,10 +35,10 @@ describe('PendingTransactionTracker', function () {
nonceTracker: {
getGlobalLock: async () => {
return { releaseLock: () => {} }
- }
+ },
},
- getPendingTransactions: () => {return []},
- getCompletedTransactions: () => {return []},
+ getPendingTransactions: () => { return [] },
+ getCompletedTransactions: () => { return [] },
publishTransaction: () => {},
})
})
@@ -133,22 +121,20 @@ describe('PendingTransactionTracker', function () {
})
describe('#queryPendingTxs', function () {
it('should call #_checkPendingTxs if their is no oldBlock', function (done) {
- let newBlock, oldBlock
- newBlock = { number: '0x01' }
+ let oldBlock
+ const newBlock = { number: '0x01' }
pendingTxTracker._checkPendingTxs = done
pendingTxTracker.queryPendingTxs({ oldBlock, newBlock })
})
it('should call #_checkPendingTxs if oldBlock and the newBlock have a diff of greater then 1', function (done) {
- let newBlock, oldBlock
- oldBlock = { number: '0x01' }
- newBlock = { number: '0x03' }
+ const oldBlock = { number: '0x01' }
+ const newBlock = { number: '0x03' }
pendingTxTracker._checkPendingTxs = done
pendingTxTracker.queryPendingTxs({ oldBlock, newBlock })
})
it('should not call #_checkPendingTxs if oldBlock and the newBlock have a diff of 1 or less', function (done) {
- let newBlock, oldBlock
- oldBlock = { number: '0x1' }
- newBlock = { number: '0x2' }
+ const oldBlock = { number: '0x1' }
+ const newBlock = { number: '0x2' }
pendingTxTracker._checkPendingTxs = () => {
const err = new Error('should not call #_checkPendingTxs if oldBlock and the newBlock have a diff of 1 or less')
done(err)
@@ -189,7 +175,7 @@ describe('PendingTransactionTracker', function () {
txMeta2.id = 2
txMeta3.id = 3
txList = [txMeta, txMeta2, txMeta3].map((tx) => {
- tx.processed = new Promise ((resolve) => { tx.resolve = resolve })
+ tx.processed = new Promise((resolve) => { tx.resolve = resolve })
return tx
})
})
@@ -197,7 +183,6 @@ describe('PendingTransactionTracker', function () {
it('should warp all txMeta\'s in #_checkPendingTx', function (done) {
pendingTxTracker.getPendingTransactions = () => txList
pendingTxTracker._checkPendingTx = (tx) => { tx.resolve(tx) }
- const list = txList.map
Promise.all(txList.map((tx) => tx.processed))
.then((txCompletedList) => done())
.catch(done)
@@ -207,11 +192,11 @@ describe('PendingTransactionTracker', function () {
})
describe('#resubmitPendingTxs', function () {
- const blockStub = { number: '0x0' };
+ const blockStub = { number: '0x0' }
beforeEach(function () {
const txMeta2 = txMeta3 = txMeta
txList = [txMeta, txMeta2, txMeta3].map((tx) => {
- tx.processed = new Promise ((resolve) => { tx.resolve = resolve })
+ tx.processed = new Promise((resolve) => { tx.resolve = resolve })
return tx
})
})
@@ -228,7 +213,7 @@ describe('PendingTransactionTracker', function () {
pendingTxTracker.resubmitPendingTxs(blockStub)
})
it('should not emit \'tx:failed\' if the txMeta throws a known txError', function (done) {
- knownErrors =[
+ knownErrors = [
// geth
' Replacement transaction Underpriced ',
' known transaction',
@@ -275,7 +260,7 @@ describe('PendingTransactionTracker', function () {
})
describe('#_resubmitTx', function () {
const mockFirstRetryBlockNumber = '0x1'
- let txMetaToTestExponentialBackoff
+ let txMetaToTestExponentialBackoff, enoughBalance
beforeEach(() => {
pendingTxTracker.getBalance = (address) => {
@@ -298,7 +283,7 @@ describe('PendingTransactionTracker', function () {
})
it('should publish the transaction', function (done) {
- const enoughBalance = '0x100000'
+ enoughBalance = '0x100000'
// Stubbing out current account state:
// Adding the fake tx:
@@ -313,7 +298,7 @@ describe('PendingTransactionTracker', function () {
})
it('should not publish the transaction if the limit of retries has been exceeded', function (done) {
- const enoughBalance = '0x100000'
+ enoughBalance = '0x100000'
const mockLatestBlockNumber = '0x5'
pendingTxTracker._resubmitTx(txMetaToTestExponentialBackoff, mockLatestBlockNumber)
@@ -327,7 +312,7 @@ describe('PendingTransactionTracker', function () {
})
it('should publish the transaction if the number of blocks since last retry exceeds the last set limit', function (done) {
- const enoughBalance = '0x100000'
+ enoughBalance = '0x100000'
const mockLatestBlockNumber = '0x11'
pendingTxTracker._resubmitTx(txMetaToTestExponentialBackoff, mockLatestBlockNumber)
@@ -342,8 +327,8 @@ describe('PendingTransactionTracker', function () {
})
describe('#_checkIfNonceIsTaken', function () {
- beforeEach ( function () {
- let confirmedTxList = [{
+ beforeEach(function () {
+ const confirmedTxList = [{
id: 1,
hash: '0x0593ee121b92e10d63150ad08b4b8f9c7857d1bd160195ee648fb9a0f8d00eeb',
status: 'confirmed',
diff --git a/test/unit/app/controllers/transactions/recipient-blacklist-checker-test.js b/test/unit/app/controllers/transactions/recipient-blacklist-checker-test.js
index 56e8d50db..cb413545f 100644
--- a/test/unit/app/controllers/transactions/recipient-blacklist-checker-test.js
+++ b/test/unit/app/controllers/transactions/recipient-blacklist-checker-test.js
@@ -28,7 +28,7 @@ describe('Recipient Blacklist Checker', function () {
it('does not fail on test networks', function () {
let callCount = 0
const networks = [ROPSTEN_CODE, RINKEYBY_CODE, KOVAN_CODE]
- for (let networkId in networks) {
+ for (const networkId in networks) {
publicAccounts.forEach((account) => {
recipientBlackListChecker.checkAccount(networkId, account)
callCount++
@@ -61,7 +61,7 @@ describe('Recipient Blacklist Checker', function () {
} catch (err) {
assert.equal(err.message, 'Recipient is a public account')
}
- })
+ })
it('fails for public account - lowercase', async function () {
const mainnetId = 1
@@ -72,6 +72,6 @@ describe('Recipient Blacklist Checker', function () {
} catch (err) {
assert.equal(err.message, 'Recipient is a public account')
}
- })
+ })
})
})
diff --git a/test/unit/app/controllers/transactions/tx-controller-test.js b/test/unit/app/controllers/transactions/tx-controller-test.js
index 9bdfe7c1a..26dc7b656 100644
--- a/test/unit/app/controllers/transactions/tx-controller-test.js
+++ b/test/unit/app/controllers/transactions/tx-controller-test.js
@@ -1,20 +1,17 @@
const assert = require('assert')
const ethUtil = require('ethereumjs-util')
const EthTx = require('ethereumjs-tx')
-const EthjsQuery = require('ethjs-query')
const ObservableStore = require('obs-store')
const sinon = require('sinon')
const TransactionController = require('../../../../../app/scripts/controllers/transactions')
-const TxGasUtils = require('../../../../../app/scripts/controllers/transactions/tx-gas-utils')
const { createTestProviderTools, getTestAccounts } = require('../../../../stub/provider')
const noop = () => true
const currentNetworkId = 42
-const otherNetworkId = 36
describe('Transaction Controller', function () {
- let txController, provider, providerResultStub, query, fromAccount
+ let txController, provider, providerResultStub, fromAccount
beforeEach(function () {
providerResultStub = {
@@ -24,7 +21,6 @@ describe('Transaction Controller', function () {
eth_getCode: '0x',
}
provider = createTestProviderTools({ scaffold: providerResultStub }).provider
- query = new EthjsQuery(provider)
fromAccount = getTestAccounts()[0]
txController = new TransactionController({
@@ -357,9 +353,16 @@ describe('Transaction Controller', function () {
])
})
- it('should set the transaction to rejected from unapproved', async function () {
- await txController.cancelTransaction(0)
- assert.equal(txController.txStateManager.getTx(0).status, 'rejected')
+ it('should emit a status change to rejected', function (done) {
+ txController.once('tx:status-update', (txId, status) => {
+ try {
+ assert.equal(status, 'rejected', 'status should e rejected')
+ assert.equal(txId, 0, 'id should e 0')
+ done()
+ } catch (e) { done(e) }
+ })
+
+ txController.cancelTransaction(0)
})
})
@@ -388,7 +391,7 @@ describe('Transaction Controller', function () {
describe('#retryTransaction', function () {
it('should create a new txMeta with the same txParams as the original one', function (done) {
- let txParams = {
+ const txParams = {
nonce: '0x00',
from: '0xB09d8505E1F4EF1CeA089D47094f5DD3464083d4',
to: '0xB09d8505E1F4EF1CeA089D47094f5DD3464083d4',
diff --git a/test/unit/app/controllers/transactions/tx-gas-util-test.js b/test/unit/app/controllers/transactions/tx-gas-util-test.js
index d1ee86033..31defd6ed 100644
--- a/test/unit/app/controllers/transactions/tx-gas-util-test.js
+++ b/test/unit/app/controllers/transactions/tx-gas-util-test.js
@@ -1,6 +1,5 @@
const assert = require('assert')
const Transaction = require('ethereumjs-tx')
-const BN = require('bn.js')
const { hexToBn, bnToHex } = require('../../../../../app/scripts/lib/util')
diff --git a/test/unit/app/controllers/transactions/tx-state-history-helper-test.js b/test/unit/app/controllers/transactions/tx-state-history-helper-test.js
index f4c3a6be1..fba0e7fda 100644
--- a/test/unit/app/controllers/transactions/tx-state-history-helper-test.js
+++ b/test/unit/app/controllers/transactions/tx-state-history-helper-test.js
@@ -2,16 +2,16 @@ const assert = require('assert')
const txStateHistoryHelper = require('../../../../../app/scripts/controllers/transactions/lib/tx-state-history-helper')
const testVault = require('../../../../data/v17-long-history.json')
-describe ('Transaction state history helper', function () {
+describe('Transaction state history helper', function () {
describe('#snapshotFromTxMeta', function () {
it('should clone deep', function () {
const input = {
foo: {
bar: {
- bam: 'baz'
- }
- }
+ bam: 'baz',
+ },
+ },
}
const output = txStateHistoryHelper.snapshotFromTxMeta(input)
assert('foo' in output, 'has a foo key')
@@ -50,14 +50,14 @@ describe ('Transaction state history helper', function () {
it('replaying history does not mutate the original obj', function () {
const initialState = { test: true, message: 'hello', value: 1 }
const diff1 = [{
- "op": "replace",
- "path": "/message",
- "value": "haay",
+ 'op': 'replace',
+ 'path': '/message',
+ 'value': 'haay',
}]
const diff2 = [{
- "op": "replace",
- "path": "/value",
- "value": 2,
+ 'op': 'replace',
+ 'path': '/value',
+ 'value': 2,
}]
const history = [initialState, diff1, diff2]
@@ -72,15 +72,15 @@ describe ('Transaction state history helper', function () {
describe('#generateHistoryEntry', function () {
- function generateHistoryEntryTest(note) {
+ function generateHistoryEntryTest (note) {
const prevState = {
someValue: 'value 1',
foo: {
bar: {
- bam: 'baz'
- }
- }
+ bam: 'baz',
+ },
+ },
}
const nextState = {
@@ -89,9 +89,9 @@ describe ('Transaction state history helper', function () {
foo: {
newPropFirstLevel: 'new property - first level',
bar: {
- bam: 'baz'
- }
- }
+ bam: 'baz',
+ },
+ },
}
const before = new Date().getTime()
@@ -106,8 +106,7 @@ describe ('Transaction state history helper', function () {
assert.equal(result[0].path, expectedEntry1.path)
assert.equal(result[0].value, expectedEntry1.value)
assert.equal(result[0].value, expectedEntry1.value)
- if (note)
- assert.equal(result[0].note, note)
+ if (note) { assert.equal(result[0].note, note) }
assert.ok(result[0].timestamp >= before && result[0].timestamp <= after)
@@ -124,6 +123,6 @@ describe ('Transaction state history helper', function () {
it('should add note to first entry', function () {
generateHistoryEntryTest('custom note')
- })
+ })
})
-}) \ No newline at end of file
+})
diff --git a/test/unit/app/controllers/transactions/tx-state-manager-test.js b/test/unit/app/controllers/transactions/tx-state-manager-test.js
index 20bc08b94..88bdaa60e 100644
--- a/test/unit/app/controllers/transactions/tx-state-manager-test.js
+++ b/test/unit/app/controllers/transactions/tx-state-manager-test.js
@@ -1,6 +1,4 @@
const assert = require('assert')
-const clone = require('clone')
-const ObservableStore = require('obs-store')
const TxStateManager = require('../../../../../app/scripts/controllers/transactions/tx-state-manager')
const txStateHistoryHelper = require('../../../../../app/scripts/controllers/transactions/lib/tx-state-history-helper')
const noop = () => true
@@ -16,23 +14,23 @@ describe('TransactionStateManager', function () {
transactions: [],
},
txHistoryLimit: 10,
- getNetwork: () => currentNetworkId
+ getNetwork: () => currentNetworkId,
})
})
describe('#setTxStatusSigned', function () {
it('sets the tx status to signed', function () {
- let tx = { id: 1, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} }
+ const tx = { id: 1, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} }
txStateManager.addTx(tx, noop)
txStateManager.setTxStatusSigned(1)
- let result = txStateManager.getTxList()
+ const result = txStateManager.getTxList()
assert.ok(Array.isArray(result))
assert.equal(result.length, 1)
assert.equal(result[0].status, 'signed')
})
it('should emit a signed event to signal the exciton of callback', (done) => {
- let tx = { id: 1, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} }
+ const tx = { id: 1, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} }
const noop = function () {
assert(true, 'event listener has been triggered and noop executed')
done()
@@ -45,22 +43,24 @@ describe('TransactionStateManager', function () {
})
describe('#setTxStatusRejected', function () {
- it('sets the tx status to rejected', function () {
- let tx = { id: 1, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} }
+ it('sets the tx status to rejected and removes it from history', function () {
+ const tx = { id: 1, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} }
txStateManager.addTx(tx)
txStateManager.setTxStatusRejected(1)
- let result = txStateManager.getTxList()
+ const result = txStateManager.getTxList()
assert.ok(Array.isArray(result))
- assert.equal(result.length, 1)
- assert.equal(result[0].status, 'rejected')
+ assert.equal(result.length, 0)
})
it('should emit a rejected event to signal the exciton of callback', (done) => {
- let tx = { id: 1, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} }
+ const tx = { id: 1, status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} }
txStateManager.addTx(tx)
const noop = function (err, txId) {
- assert(true, 'event listener has been triggered and noop executed')
- done()
+ if (err) {
+ console.log('Error: ', err)
+ }
+ assert(true, 'event listener has been triggered and noop executed')
+ done()
}
txStateManager.on('1:rejected', noop)
txStateManager.setTxStatusRejected(1)
@@ -69,7 +69,7 @@ describe('TransactionStateManager', function () {
describe('#getFullTxList', function () {
it('when new should return empty array', function () {
- let result = txStateManager.getTxList()
+ const result = txStateManager.getTxList()
assert.ok(Array.isArray(result))
assert.equal(result.length, 0)
})
@@ -77,7 +77,7 @@ describe('TransactionStateManager', function () {
describe('#getTxList', function () {
it('when new should return empty array', function () {
- let result = txStateManager.getTxList()
+ const result = txStateManager.getTxList()
assert.ok(Array.isArray(result))
assert.equal(result.length, 0)
})
@@ -85,21 +85,21 @@ describe('TransactionStateManager', function () {
describe('#addTx', function () {
it('adds a tx returned in getTxList', function () {
- let tx = { id: 1, status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams: {} }
+ const tx = { id: 1, status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams: {} }
txStateManager.addTx(tx, noop)
- let result = txStateManager.getTxList()
+ const result = txStateManager.getTxList()
assert.ok(Array.isArray(result))
assert.equal(result.length, 1)
assert.equal(result[0].id, 1)
})
it('does not override txs from other networks', function () {
- let tx = { id: 1, status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams: {} }
- let tx2 = { id: 2, status: 'confirmed', metamaskNetworkId: otherNetworkId, txParams: {} }
+ const tx = { id: 1, status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams: {} }
+ const tx2 = { id: 2, status: 'confirmed', metamaskNetworkId: otherNetworkId, txParams: {} }
txStateManager.addTx(tx, noop)
txStateManager.addTx(tx2, noop)
- let result = txStateManager.getFullTxList()
- let result2 = txStateManager.getTxList()
+ const result = txStateManager.getFullTxList()
+ const result2 = txStateManager.getTxList()
assert.equal(result.length, 2, 'txs were deleted')
assert.equal(result2.length, 1, 'incorrect number of txs on network.')
})
@@ -110,7 +110,7 @@ describe('TransactionStateManager', function () {
const tx = { id: i, time: new Date(), status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams: {} }
txStateManager.addTx(tx, noop)
}
- let result = txStateManager.getTxList()
+ const result = txStateManager.getTxList()
assert.equal(result.length, limit, `limit of ${limit} txs enforced`)
assert.equal(result[0].id, 1, 'early txs truncted')
})
@@ -121,20 +121,20 @@ describe('TransactionStateManager', function () {
const tx = { id: i, time: new Date(), status: 'rejected', metamaskNetworkId: currentNetworkId, txParams: {} }
txStateManager.addTx(tx, noop)
}
- let result = txStateManager.getTxList()
+ const result = txStateManager.getTxList()
assert.equal(result.length, limit, `limit of ${limit} txs enforced`)
assert.equal(result[0].id, 1, 'early txs truncted')
})
it('cuts off early txs beyond a limit but does not cut unapproved txs', function () {
- let unconfirmedTx = { id: 0, time: new Date(), status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} }
+ const unconfirmedTx = { id: 0, time: new Date(), status: 'unapproved', metamaskNetworkId: currentNetworkId, txParams: {} }
txStateManager.addTx(unconfirmedTx, noop)
const limit = txStateManager.txHistoryLimit
for (let i = 1; i < limit + 1; i++) {
const tx = { id: i, time: new Date(), status: 'confirmed', metamaskNetworkId: currentNetworkId, txParams: {} }
txStateManager.addTx(tx, noop)
}
- let result = txStateManager.getTxList()
+ const result = txStateManager.getTxList()
assert.equal(result.length, limit, `limit of ${limit} txs enforced`)
assert.equal(result[0].id, 0, 'first tx should still be there')
assert.equal(result[0].status, 'unapproved', 'first tx should be unapproved')
@@ -149,7 +149,7 @@ describe('TransactionStateManager', function () {
const txMeta = txStateManager.getTx('1')
txMeta.hash = 'foo'
txStateManager.updateTx(txMeta)
- let result = txStateManager.getTx('1')
+ const result = txStateManager.getTx('1')
assert.equal(result.hash, 'foo')
})
@@ -166,8 +166,6 @@ describe('TransactionStateManager', function () {
},
}
- const updatedMeta = clone(txMeta)
-
txStateManager.addTx(txMeta)
const updatedTx = txStateManager.getTx('1')
// verify tx was initialized correctly
@@ -185,7 +183,7 @@ describe('TransactionStateManager', function () {
// validate history was updated
assert.equal(result.history.length, 2, 'two history items (initial + diff)')
assert.equal(result.history[1].length, 1, 'two history state items (initial + diff)')
-
+
const expectedEntry = { op: 'replace', path: '/txParams/gasPrice', value: desiredGasPrice }
assert.deepEqual(result.history[1][0].op, expectedEntry.op, 'two history items (initial + diff) operation')
assert.deepEqual(result.history[1][0].path, expectedEntry.path, 'two history items (initial + diff) path')
@@ -288,4 +286,18 @@ describe('TransactionStateManager', function () {
})
})
+
+ describe('#_removeTx', function () {
+ it('should remove the transaction from the storage', () => {
+ txStateManager._saveTxList([ {id: 1} ])
+ txStateManager._removeTx(1)
+ assert(!txStateManager.getFullTxList().length, 'txList should be empty')
+ })
+
+ it('should only remove the transaction with ID 1 from the storage', () => {
+ txStateManager._saveTxList([ {id: 1}, {id: 2} ])
+ txStateManager._removeTx(1)
+ assert.equal(txStateManager.getFullTxList()[0].id, 2, 'txList should have a id of 2')
+ })
+ })
})
diff --git a/test/unit/app/controllers/transactions/tx-utils-test.js b/test/unit/app/controllers/transactions/tx-utils-test.js
index 115127f85..029fab4d5 100644
--- a/test/unit/app/controllers/transactions/tx-utils-test.js
+++ b/test/unit/app/controllers/transactions/tx-utils-test.js
@@ -27,7 +27,7 @@ describe('txUtils', function () {
describe('#normalizeTxParams', () => {
it('should normalize txParams', () => {
- let txParams = {
+ const txParams = {
chainId: '0x1',
from: 'a7df1beDBF813f57096dF77FCd515f0B3900e402',
to: null,
@@ -91,7 +91,7 @@ describe('txUtils', function () {
assert.throws(() => { txUtils.validateFrom(txParams) }, Error, `Invalid from address`)
// should run
- txParams.from ='0x1678a085c290ebd122dc42cba69373b5953b831d'
+ txParams.from = '0x1678a085c290ebd122dc42cba69373b5953b831d'
txUtils.validateFrom(txParams)
})
})
diff --git a/test/unit/app/edge-encryptor-test.js b/test/unit/app/edge-encryptor-test.js
index cc9777389..1a6255b36 100644
--- a/test/unit/app/edge-encryptor-test.js
+++ b/test/unit/app/edge-encryptor-test.js
@@ -11,7 +11,7 @@ global.crypto = global.crypto || {
array[i] = Math.random() * 100
}
return array
- }
+ },
}
describe('EdgeEncryptor', function () {
@@ -33,10 +33,10 @@ describe('EdgeEncryptor', function () {
it('should return proper format.', function (done) {
edgeEncryptor.encrypt(password, data)
.then(function (encryptedData) {
- let encryptedObject = JSON.parse(encryptedData)
+ const encryptedObject = JSON.parse(encryptedData)
assert.ok(encryptedObject.data, 'there is no data')
- assert.ok(encryptedObject.iv && encryptedObject.iv.length != 0, 'there is no iv')
- assert.ok(encryptedObject.salt && encryptedObject.salt.length != 0, 'there is no salt')
+ assert.ok(encryptedObject.iv && encryptedObject.iv.length !== 0, 'there is no iv')
+ assert.ok(encryptedObject.salt && encryptedObject.salt.length !== 0, 'there is no salt')
done()
}).catch(function (err) {
done(err)
@@ -56,7 +56,7 @@ describe('EdgeEncryptor', function () {
assert.notEqual(encryptedData[1].length, 0)
done()
})
- })
+ })
})
describe('decrypt', function () {
diff --git a/test/unit/app/nodeify-test.js b/test/unit/app/nodeify-test.js
index 901603c8b..938b76c68 100644
--- a/test/unit/app/nodeify-test.js
+++ b/test/unit/app/nodeify-test.js
@@ -13,8 +13,12 @@ describe('nodeify', function () {
it('should retain original context', function (done) {
var nodified = nodeify(obj.promiseFunc, obj)
nodified('baz', function (err, res) {
- assert.equal(res, 'barbaz')
- done()
+ if (!err) {
+ assert.equal(res, 'barbaz')
+ done()
+ } else {
+ done(new Error(err.toString()))
+ }
})
})
diff --git a/test/unit/app/pending-balance-test.js b/test/unit/app/pending-balance-test.js
index 1418e4a4e..508635c46 100644
--- a/test/unit/app/pending-balance-test.js
+++ b/test/unit/app/pending-balance-test.js
@@ -2,7 +2,6 @@ const assert = require('assert')
const PendingBalanceCalculator = require('../../../app/scripts/lib/pending-balance-calculator')
const MockTxGen = require('../../lib/mock-tx-gen')
const BN = require('ethereumjs-util').BN
-let providerResultStub = {}
const zeroBn = new BN(0)
const etherBn = new BN(String(1e18))
@@ -20,7 +19,7 @@ describe('PendingBalanceCalculator', function () {
value: ether,
gasPrice: '0x0',
gas: '0x0',
- }
+ },
}, { count: 1 })
const balanceCalculator = generateBalanceCalcWith([], zeroBn)
@@ -36,7 +35,7 @@ describe('PendingBalanceCalculator', function () {
value: '0x0',
gasPrice: '0x2',
gas: '0x3',
- }
+ },
}, { count: 1 })
const balanceCalculator = generateBalanceCalcWith([], zeroBn)
@@ -66,7 +65,7 @@ describe('PendingBalanceCalculator', function () {
value: ether,
gasPrice: '0x0',
gas: '0x0',
- }
+ },
}, { count: 1 })
balanceCalculator = generateBalanceCalcWith(pendingTxs, etherBn)
diff --git a/test/unit/app/seed-phrase-verifier-test.js b/test/unit/app/seed-phrase-verifier-test.js
index b0da534da..d8720d5a0 100644
--- a/test/unit/app/seed-phrase-verifier-test.js
+++ b/test/unit/app/seed-phrase-verifier-test.js
@@ -9,11 +9,10 @@ describe('SeedPhraseVerifier', function () {
describe('verifyAccounts', function () {
- let password = 'passw0rd1'
- let hdKeyTree = 'HD Key Tree'
+ const password = 'passw0rd1'
+ const hdKeyTree = 'HD Key Tree'
let keyringController
- let vault
let primaryKeyring
beforeEach(async function () {
@@ -24,60 +23,60 @@ describe('SeedPhraseVerifier', function () {
assert(keyringController)
- vault = await keyringController.createNewVaultAndKeychain(password)
+ await keyringController.createNewVaultAndKeychain(password)
primaryKeyring = keyringController.getKeyringsByType(hdKeyTree)[0]
})
it('should be able to verify created account with seed words', async function () {
- let createdAccounts = await primaryKeyring.getAccounts()
+ const createdAccounts = await primaryKeyring.getAccounts()
assert.equal(createdAccounts.length, 1)
- let serialized = await primaryKeyring.serialize()
- let seedWords = serialized.mnemonic
+ const serialized = await primaryKeyring.serialize()
+ const seedWords = serialized.mnemonic
assert.notEqual(seedWords.length, 0)
-
- let result = await seedPhraseVerifier.verifyAccounts(createdAccounts, seedWords)
+
+ await seedPhraseVerifier.verifyAccounts(createdAccounts, seedWords)
})
it('should be able to verify created account (upper case) with seed words', async function () {
- let createdAccounts = await primaryKeyring.getAccounts()
+ const createdAccounts = await primaryKeyring.getAccounts()
assert.equal(createdAccounts.length, 1)
- let upperCaseAccounts = [createdAccounts[0].toUpperCase()]
+ const upperCaseAccounts = [createdAccounts[0].toUpperCase()]
- let serialized = await primaryKeyring.serialize()
- let seedWords = serialized.mnemonic
+ const serialized = await primaryKeyring.serialize()
+ const seedWords = serialized.mnemonic
assert.notEqual(seedWords.length, 0)
-
- let result = await seedPhraseVerifier.verifyAccounts(upperCaseAccounts, seedWords)
+
+ await seedPhraseVerifier.verifyAccounts(upperCaseAccounts, seedWords)
})
it('should be able to verify created account (lower case) with seed words', async function () {
- let createdAccounts = await primaryKeyring.getAccounts()
+ const createdAccounts = await primaryKeyring.getAccounts()
assert.equal(createdAccounts.length, 1)
- let lowerCaseAccounts = [createdAccounts[0].toLowerCase()]
+ const lowerCaseAccounts = [createdAccounts[0].toLowerCase()]
- let serialized = await primaryKeyring.serialize()
- let seedWords = serialized.mnemonic
+ const serialized = await primaryKeyring.serialize()
+ const seedWords = serialized.mnemonic
assert.notEqual(seedWords.length, 0)
-
- let result = await seedPhraseVerifier.verifyAccounts(lowerCaseAccounts, seedWords)
+
+ await seedPhraseVerifier.verifyAccounts(lowerCaseAccounts, seedWords)
})
it('should return error with good but different seed words', async function () {
- let createdAccounts = await primaryKeyring.getAccounts()
+ const createdAccounts = await primaryKeyring.getAccounts()
assert.equal(createdAccounts.length, 1)
- let serialized = await primaryKeyring.serialize()
- let seedWords = 'debris dizzy just program just float decrease vacant alarm reduce speak stadium'
-
- try {
- let result = await seedPhraseVerifier.verifyAccounts(createdAccounts, seedWords)
- assert.fail("Should reject")
+ await primaryKeyring.serialize()
+ const seedWords = 'debris dizzy just program just float decrease vacant alarm reduce speak stadium'
+
+ try {
+ await seedPhraseVerifier.verifyAccounts(createdAccounts, seedWords)
+ assert.fail('Should reject')
} catch (err) {
assert.ok(err.message.indexOf('Not identical accounts!') >= 0, 'Wrong error message')
}
@@ -85,15 +84,15 @@ describe('SeedPhraseVerifier', function () {
it('should return error with undefined existing accounts', async function () {
- let createdAccounts = await primaryKeyring.getAccounts()
+ const createdAccounts = await primaryKeyring.getAccounts()
assert.equal(createdAccounts.length, 1)
- let serialized = await primaryKeyring.serialize()
- let seedWords = 'debris dizzy just program just float decrease vacant alarm reduce speak stadium'
+ await primaryKeyring.serialize()
+ const seedWords = 'debris dizzy just program just float decrease vacant alarm reduce speak stadium'
- try {
- let result = await seedPhraseVerifier.verifyAccounts(undefined, seedWords)
- assert.fail("Should reject")
+ try {
+ await seedPhraseVerifier.verifyAccounts(undefined, seedWords)
+ assert.fail('Should reject')
} catch (err) {
assert.equal(err.message, 'No created accounts defined.')
}
@@ -101,15 +100,15 @@ describe('SeedPhraseVerifier', function () {
it('should return error with empty accounts array', async function () {
- let createdAccounts = await primaryKeyring.getAccounts()
+ const createdAccounts = await primaryKeyring.getAccounts()
assert.equal(createdAccounts.length, 1)
- let serialized = await primaryKeyring.serialize()
- let seedWords = 'debris dizzy just program just float decrease vacant alarm reduce speak stadium'
+ await primaryKeyring.serialize()
+ const seedWords = 'debris dizzy just program just float decrease vacant alarm reduce speak stadium'
- try {
- let result = await seedPhraseVerifier.verifyAccounts([], seedWords)
- assert.fail("Should reject")
+ try {
+ await seedPhraseVerifier.verifyAccounts([], seedWords)
+ assert.fail('Should reject')
} catch (err) {
assert.equal(err.message, 'No created accounts defined.')
}
@@ -117,17 +116,17 @@ describe('SeedPhraseVerifier', function () {
it('should be able to verify more than one created account with seed words', async function () {
- const keyState = await keyringController.addNewAccount(primaryKeyring)
- const keyState2 = await keyringController.addNewAccount(primaryKeyring)
+ await keyringController.addNewAccount(primaryKeyring)
+ await keyringController.addNewAccount(primaryKeyring)
- let createdAccounts = await primaryKeyring.getAccounts()
+ const createdAccounts = await primaryKeyring.getAccounts()
assert.equal(createdAccounts.length, 3)
- let serialized = await primaryKeyring.serialize()
- let seedWords = serialized.mnemonic
+ const serialized = await primaryKeyring.serialize()
+ const seedWords = serialized.mnemonic
assert.notEqual(seedWords.length, 0)
-
- let result = await seedPhraseVerifier.verifyAccounts(createdAccounts, seedWords)
+
+ await seedPhraseVerifier.verifyAccounts(createdAccounts, seedWords)
})
})
})
diff --git a/test/unit/app/util-test.js b/test/unit/app/util-test.js
index 670bc4d22..656b22d92 100644
--- a/test/unit/app/util-test.js
+++ b/test/unit/app/util-test.js
@@ -38,4 +38,4 @@ describe('SufficientBalance', function () {
const result = sufficientBalance(tx, balance)
assert.ok(!result, 'insufficient balance found.')
})
-}) \ No newline at end of file
+})
diff --git a/test/unit/components/balance-component-test.js b/test/unit/components/balance-component-test.js
index 9b1e82acf..81e6fdf9e 100644
--- a/test/unit/components/balance-component-test.js
+++ b/test/unit/components/balance-component-test.js
@@ -8,7 +8,7 @@ const mockState = {
accounts: { abc: {} },
network: 1,
selectedAddress: 'abc',
- }
+ },
}
describe('BalanceComponent', function () {
diff --git a/test/unit/components/bn-as-decimal-input-test.js b/test/unit/components/bn-as-decimal-input-test.js
index 7b9d9814f..fab396548 100644
--- a/test/unit/components/bn-as-decimal-input-test.js
+++ b/test/unit/components/bn-as-decimal-input-test.js
@@ -52,13 +52,13 @@ describe('BnInput', function () {
it('can tolerate wei precision', function (done) {
const renderer = ReactTestUtils.createRenderer()
- let valueStr = '1000000000'
+ const valueStr = '1000000000'
const value = new BN(valueStr, 10)
const inputStr = '1.000000001'
- let targetStr = '1000000001'
+ const targetStr = '1000000001'
const target = new BN(targetStr, 10)
diff --git a/test/unit/components/pending-tx-test.js b/test/unit/components/pending-tx-test.js
deleted file mode 100644
index c6c588e1c..000000000
--- a/test/unit/components/pending-tx-test.js
+++ /dev/null
@@ -1,67 +0,0 @@
-const assert = require('assert')
-const h = require('react-hyperscript')
-const PendingTx = require('../../../ui/app/components/pending-tx')
-const ethUtil = require('ethereumjs-util')
-
-const { createMockStore } = require('redux-test-utils')
-const { shallowWithStore } = require('../../lib/shallow-with-store')
-
-const identities = { abc: {}, def: {} }
-const mockState = {
- metamask: {
- accounts: { abc: {} },
- identities,
- conversionRate: 10,
- selectedAddress: 'abc',
- }
-}
-
-describe('PendingTx', function () {
- const gasPrice = '0x4A817C800' // 20 Gwei
- const txData = {
- 'id': 5021615666270214,
- 'time': 1494458763011,
- 'status': 'unapproved',
- 'metamaskNetworkId': '1494442339676',
- 'txParams': {
- 'from': '0xfdea65c8e26263f6d9a1b5de9555d2931a33b826',
- 'to': '0xc5b8dbac4c1d3f152cdeb400e2313f309c410acb',
- 'value': '0xde0b6b3a7640000',
- gasPrice,
- 'gas': '0x7b0c',
- },
- 'gasLimitSpecified': false,
- 'estimatedGas': '0x5208',
- }
- const newGasPrice = '0x77359400'
-
- const computedBalances = {}
- computedBalances[Object.keys(identities)[0]] = {
- ethBalance: '0x00000000000000056bc75e2d63100000',
- }
- const props = {
- txData,
- computedBalances,
- sendTransaction: (txMeta, event) => {
- // Assert changes:
- const result = ethUtil.addHexPrefix(txMeta.txParams.gasPrice)
- assert.notEqual(result, gasPrice, 'gas price should change')
- assert.equal(result, newGasPrice, 'gas price assigned.')
- },
- }
-
- let pendingTxComponent
- let store
- let component
- beforeEach(function () {
- store = createMockStore(mockState)
- component = shallowWithStore(h(PendingTx, props), store)
- pendingTxComponent = component
- })
-
- it('should render correctly', function (done) {
- assert.equal(pendingTxComponent.props().identities, identities)
- done()
- })
-})
-
diff --git a/test/unit/migrations/022-test.js b/test/unit/migrations/022-test.js
index 1333d929d..f8ee00e38 100644
--- a/test/unit/migrations/022-test.js
+++ b/test/unit/migrations/022-test.js
@@ -2,14 +2,14 @@ const assert = require('assert')
const migration22 = require('../../../app/scripts/migrations/022')
const properTime = (new Date()).getTime()
const storage = {
- "meta": {},
- "data": {
- "TransactionController": {
- "transactions": [
- { "status": "submitted" },
- { "status": "submitted", "submittedTime": properTime },
- {"status": "confirmed"},
- ]
+ 'meta': {},
+ 'data': {
+ 'TransactionController': {
+ 'transactions': [
+ { 'status': 'submitted' },
+ { 'status': 'submitted', 'submittedTime': properTime },
+ {'status': 'confirmed'},
+ ],
},
},
}
diff --git a/test/unit/migrations/023-test.js b/test/unit/migrations/023-test.js
index be432d9fa..7da94448d 100644
--- a/test/unit/migrations/023-test.js
+++ b/test/unit/migrations/023-test.js
@@ -1,12 +1,11 @@
const assert = require('assert')
const migration23 = require('../../../app/scripts/migrations/023')
-const properTime = (new Date()).getTime()
const storage = {
- "meta": {},
- "data": {
- "TransactionController": {
- "transactions": [
- ]
+ 'meta': {},
+ 'data': {
+ 'TransactionController': {
+ 'transactions': [
+ ],
},
},
}
@@ -53,7 +52,6 @@ while (transactions20.length < 20) {
}
-
storage.data.TransactionController.transactions = transactions
describe('storage is migrated successfully and the proper transactions are remove from state', () => {
diff --git a/test/unit/migrations/024-test.js b/test/unit/migrations/024-test.js
index c3c03d06b..c7b0611bc 100644
--- a/test/unit/migrations/024-test.js
+++ b/test/unit/migrations/024-test.js
@@ -4,13 +4,12 @@ const firstTimeState = {
meta: {},
data: require('../../../app/scripts/first-time-state'),
}
-const properTime = (new Date()).getTime()
const storage = {
- "meta": {},
- "data": {
- "TransactionController": {
- "transactions": [
- ]
+ 'meta': {},
+ 'data': {
+ 'TransactionController': {
+ 'transactions': [
+ ],
},
},
}
diff --git a/test/unit/migrations/025-test.js b/test/unit/migrations/025-test.js
index 76c25dbb6..1e56913a1 100644
--- a/test/unit/migrations/025-test.js
+++ b/test/unit/migrations/025-test.js
@@ -6,11 +6,11 @@ const firstTimeState = {
}
const storage = {
- "meta": {},
- "data": {
- "TransactionController": {
- "transactions": [
- ]
+ 'meta': {},
+ 'data': {
+ 'TransactionController': {
+ 'transactions': [
+ ],
},
},
}
diff --git a/test/unit/migrations/027-test.js b/test/unit/migrations/027-test.js
new file mode 100644
index 000000000..3ec9f0c0e
--- /dev/null
+++ b/test/unit/migrations/027-test.js
@@ -0,0 +1,50 @@
+const assert = require('assert')
+const migration27 = require('../../../app/scripts/migrations/027')
+
+const oldStorage = {
+ 'meta': {},
+ 'data': {
+ 'TransactionController': {
+ 'transactions': [
+ ],
+ },
+ },
+}
+
+const transactions = []
+
+
+while (transactions.length < 9) {
+ transactions.push({status: 'rejected'})
+ transactions.push({status: 'unapproved'})
+ transactions.push({status: 'approved'})
+}
+
+
+oldStorage.data.TransactionController.transactions = transactions
+
+describe('migration #27', () => {
+ it('should remove rejected transactions', (done) => {
+ migration27.migrate(oldStorage)
+ .then((newStorage) => {
+ const newTransactions = newStorage.data.TransactionController.transactions
+ assert.equal(newTransactions.length, 6, 'transactions is expected to have the length of 6')
+ newTransactions.forEach((txMeta) => {
+ if (txMeta.status === 'rejected') done(new Error('transaction was found with a status of rejected'))
+ })
+ done()
+ })
+ .catch(done)
+ })
+
+ it('should successfully migrate first time state', (done) => {
+ migration27.migrate({
+ meta: {},
+ data: require('../../../app/scripts/first-time-state'),
+ })
+ .then((migratedData) => {
+ assert.equal(migratedData.meta.version, migration27.version)
+ done()
+ }).catch(done)
+ })
+})
diff --git a/test/unit/migrations/template-test.js b/test/unit/migrations/template-test.js
index 35060e2fe..0db69d65a 100644
--- a/test/unit/migrations/template-test.js
+++ b/test/unit/migrations/template-test.js
@@ -1,6 +1,5 @@
const assert = require('assert')
const migrationTemplate = require('../../../app/scripts/migrations/template')
-const properTime = (new Date()).getTime()
const storage = {
meta: {},
data: {},
diff --git a/test/unit/responsive/components/dropdown-test.js b/test/unit/responsive/components/dropdown-test.js
index 982d8c6ec..493b01918 100644
--- a/test/unit/responsive/components/dropdown-test.js
+++ b/test/unit/responsive/components/dropdown-test.js
@@ -1,24 +1,24 @@
-const assert = require('assert');
+const assert = require('assert')
-const h = require('react-hyperscript');
-const sinon = require('sinon');
-const path = require('path');
-const Dropdown = require(path.join(__dirname, '..', '..', '..', '..', 'ui', 'app', 'components', 'dropdowns', 'index.js')).Dropdown;
+const h = require('react-hyperscript')
+const sinon = require('sinon')
+const path = require('path')
+const Dropdown = require(path.join(__dirname, '..', '..', '..', '..', 'ui', 'app', 'components', 'dropdowns', 'index.js')).Dropdown
const { createMockStore } = require('redux-test-utils')
const { mountWithStore } = require('../../../lib/shallow-with-store')
const mockState = {
metamask: {
- }
+ },
}
describe('Dropdown components', function () {
- let onClickOutside;
- let closeMenu;
- let onClick;
+ let onClickOutside
+ let closeMenu
+ let onClick
- let dropdownComponentProps = {
+ const dropdownComponentProps = {
isOpen: true,
zIndex: 11,
onClickOutside,
@@ -34,9 +34,9 @@ describe('Dropdown components', function () {
let store
let component
beforeEach(function () {
- onClickOutside = sinon.spy();
- closeMenu = sinon.spy();
- onClick = sinon.spy();
+ onClickOutside = sinon.spy()
+ closeMenu = sinon.spy()
+ onClick = sinon.spy()
store = createMockStore(mockState)
component = mountWithStore(h(
@@ -61,21 +61,21 @@ describe('Dropdown components', function () {
})
it('can render two items', function () {
- const items = dropdownComponent.find('li');
- assert.equal(items.length, 2);
- });
+ const items = dropdownComponent.find('li')
+ assert.equal(items.length, 2)
+ })
- it('closes when item clicked', function() {
- const items = dropdownComponent.find('li');
- const node = items.at(0);
- node.simulate('click');
- assert.equal(node.props().closeMenu, closeMenu);
- });
+ it('closes when item clicked', function () {
+ const items = dropdownComponent.find('li')
+ const node = items.at(0)
+ node.simulate('click')
+ assert.equal(node.props().closeMenu, closeMenu)
+ })
- it('invokes click handler when item clicked', function() {
- const items = dropdownComponent.find('li');
- const node = items.at(0);
- node.simulate('click');
- assert.equal(onClick.calledOnce, true);
- });
-});
+ it('invokes click handler when item clicked', function () {
+ const items = dropdownComponent.find('li')
+ const node = items.at(0)
+ node.simulate('click')
+ assert.equal(onClick.calledOnce, true)
+ })
+})