From b898115bada2bf7f7df908f0f7cda4d1de20d81d Mon Sep 17 00:00:00 2001 From: Ariella Vu <20778143+digiwand@users.noreply.github.com> Date: Wed, 16 Nov 2022 01:32:31 +0700 Subject: [PATCH] Jest: Add browser.runtime (webextension-polyfill) utils tests (#16483) * jest: add browser-runtime.utils tests * browser-runtime.utils: rm checkForLastErrorAndWarn - will be removing use in https://github.com/MetaMask/metamask-extension/pull/16488 --- shared/modules/browser-runtime.utils.test.js | 54 ++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 shared/modules/browser-runtime.utils.test.js diff --git a/shared/modules/browser-runtime.utils.test.js b/shared/modules/browser-runtime.utils.test.js new file mode 100644 index 000000000..b116f2d7c --- /dev/null +++ b/shared/modules/browser-runtime.utils.test.js @@ -0,0 +1,54 @@ +import sinon from 'sinon'; +import browser from 'webextension-polyfill'; +import log from 'loglevel'; +import * as BrowserRuntimeUtil from './browser-runtime.utils'; + +const mockLastError = { message: 'error', stack: [] }; + +describe('Browser Runtime Utils', () => { + beforeAll(() => { + sinon.replace(browser, 'runtime', { + lastError: undefined, + }); + }); + + describe('checkForLastError', () => { + it('should return undefined if no lastError found', () => { + expect(BrowserRuntimeUtil.checkForLastError()).toBeUndefined(); + }); + + it('should return the lastError (Error object) if lastError is found', () => { + sinon.stub(browser.runtime, 'lastError').value(mockLastError); + + expect(BrowserRuntimeUtil.checkForLastError()).toStrictEqual( + mockLastError, + ); + }); + + it('should return an Error object if the lastError is found with no stack', () => { + sinon + .stub(browser.runtime, 'lastError') + .value({ message: mockLastError.message }); + + const result = BrowserRuntimeUtil.checkForLastError(); + + expect(result).toStrictEqual(expect.any(Error)); + expect(result).toHaveProperty('stack'); + expect(result.message).toBe(mockLastError.message); + }); + }); + + describe('checkForLastErrorAndLog', () => { + it('should log and return error if error was found', () => { + sinon.stub(browser.runtime, 'lastError').value({ ...mockLastError }); + sinon.stub(log, 'error'); + + const result = BrowserRuntimeUtil.checkForLastErrorAndLog(); + + expect(log.error.calledWith(result)).toBeTruthy(); + expect(result).toStrictEqual(mockLastError); + + log.error.restore(); + }); + }); +});