Skip to content

Commit

Permalink
More browser testing
Browse files Browse the repository at this point in the history
  • Loading branch information
mtusnio committed Aug 24, 2024
1 parent 7a45259 commit ad80c69
Show file tree
Hide file tree
Showing 10 changed files with 246 additions and 114 deletions.
56 changes: 56 additions & 0 deletions browser_tests/activate.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import * as utils from "./utils";

let browser = null;
let worker = null

beforeEach(async () => {
const setupData = await utils.setupBrowser()
browser = setupData.browser
worker = setupData.worker
});

afterEach(async () => {
await browser.close();
browser = null;
worker = null
});

test("extension is disabled by default", async () => {
const page = await browser.newPage();
await page.goto("https://www.google.com/", { waitUntil: ['domcontentloaded', "networkidle2"] });
await page.bringToFront();

const status = await utils.getExtensionStatus(worker)
expect(status.storage).toEqual({})
expect(status.badgeData).toEqual({
"text": "", "color": [0, 0, 0, 0]
})
})

test("toggling the extension on/off two times works", async () => {
const page = await browser.newPage();
await page.goto("https://www.google.com/", { waitUntil: ['domcontentloaded', "networkidle2"] });
await page.bringToFront();

for (let i = 0; i < 2; i++) {
// On
await utils.toggleExtension(worker)
// Need a slight wait for the extension to trigger
await utils.wait(200)
let status = await utils.getExtensionStatus(worker)
expect(status.storage).toEqual({ "enabled": true })
expect(status.badgeData).toEqual({
"text": "On", "color": [255, 0, 0, 255]
})

// Off
await utils.toggleExtension(worker)
await utils.wait(200)
status = await utils.getExtensionStatus(worker)
expect(status.storage).toEqual({ "enabled": false })
expect(status.badgeData).toEqual({
"text": "", "color": [0, 0, 0, 0]
})
}

});
94 changes: 0 additions & 94 deletions browser_tests/index.test.js

This file was deleted.

27 changes: 27 additions & 0 deletions browser_tests/popup.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import path from 'path';
import * as utils from "./utils";


let browser = null;
let worker = null

beforeEach(async () => {
const setupData = await utils.setupBrowser()
browser = setupData.browser
worker = setupData.worker
});

afterEach(async () => {
await browser.close();
browser = null;
worker = null
});

test("popup appears when hovering over text in plain html", async () => {
const page = await browser.newPage();
await page.goto(`file://${path.resolve()}/browser_tests/testdata/plain.html`, { waitUntil: ['domcontentloaded', "networkidle2"] });
await page.bringToFront();

await utils.toggleExtension(worker)
await utils.wait(200)
})
1 change: 1 addition & 0 deletions browser_tests/testdata/plain.html
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
滚滚长江东逝水,浪花淘尽英雄。是非成败转头空:青山依旧在,几度夕阳红。白发渔樵江渚上,惯看秋月春风。一壶浊酒喜相逢:古今多少事,都付笑谈中。
54 changes: 54 additions & 0 deletions browser_tests/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import * as puppeteer from "puppeteer";

const EXTENSION_PATH = './';

async function setupBrowser() {
const browser = await puppeteer.launch({
headless: false,
args: [
`--disable-extensions-except=${EXTENSION_PATH}`,
`--load-extension=${EXTENSION_PATH}`
]
});

const workerTarget = await browser.waitForTarget(
// Assumes that there is only one service worker created by the extension and its URL ends with background.js.
target =>
target.type() === 'service_worker'
);
const worker = await workerTarget.worker()
return { browser, worker }
}

async function getExtensionStatus(worker) {
const storage = await worker.evaluate(async () => {
return await chrome.storage.local.get(["enabled"])
})
const badgeData = await worker.evaluate(async () => {
return {
"text": await chrome.action.getBadgeText({}),
"color": await chrome.action.getBadgeBackgroundColor({}),
}
})

return {
storage,
badgeData
}
}

async function toggleExtension(worker) {
await worker.evaluate(async () => {
const tabs = await chrome.tabs.query({ active: true })
await chrome.action.onClicked.dispatch(tabs[0]);
});
}

async function wait(miliseconds) {
await new Promise((r) => setTimeout(r, miliseconds));
}

export {
getExtensionStatus, setupBrowser, toggleExtension, wait
};

10 changes: 5 additions & 5 deletions lib/actions.test.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'use strict';

import * as setup from "./setup.js"
import * as actions from "./actions.js"
import * as actions from "./actions.js";
import * as setup from "./setup.js";

import { jest } from '@jest/globals';

Expand All @@ -26,7 +26,7 @@ test("if dictionary is set-up, returns an entry for the word", async () => {
setBadgeBackgroundColor = jest.spyOn(chrome.action, "setBadgeBackgroundColor").mockReturnValue();
setBadgeText = jest.spyOn(chrome.action, "setBadgeText").mockReturnValue();

await setup.activateExtension()
await setup.loadDictionary()

expect(await actions.search("律师")).toEqual([
{
Expand Down Expand Up @@ -100,7 +100,7 @@ test("if dictionary is set-up, searching for a word with special characters stri
setBadgeBackgroundColor = jest.spyOn(chrome.action, "setBadgeBackgroundColor").mockReturnValue();
setBadgeText = jest.spyOn(chrome.action, "setBadgeText").mockReturnValue();

await setup.activateExtension()
await setup.loadDictionary()

expect(await actions.search("律师 ")).toEqual([
{
Expand Down Expand Up @@ -354,7 +354,7 @@ test("enabling a tab with extension disabled does NOT send a message", async ()
test("enabling a tab with extension enabled sends a message to the tab", async () => {
const sendMessage = jest.spyOn(chrome.tabs, "sendMessage").mockReturnValue();

await setup.activateExtension()
await setup.activateExtension(10)

await actions.enableTab(5)

Expand Down
2 changes: 1 addition & 1 deletion lib/dict.test.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'use strict';

import { ZhongwenDictionary } from "./dict.js";
import { jest } from '@jest/globals';
import { ZhongwenDictionary } from "./dict.js";

jest.useFakeTimers();

Expand Down
41 changes: 30 additions & 11 deletions lib/setup.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,18 @@ function getDictionary() {
return dict
}

async function activateExtension() {
console.log("Activate")
async function activateExtension(tabId) {
console.log("Activate", tabId)
await chrome.storage.local.set({ "enabled": true })

if (!dict) {
dict = await loadDictionary()
await loadDictionary()
}

chrome.tabs.sendMessage(tabId, {
'type': 'enable',
});

await chrome.action.setBadgeBackgroundColor({
'color': [255, 0, 0, 255]
});
Expand All @@ -26,20 +30,20 @@ async function activateExtension() {
}

async function loadDictData() {
let mandarinDict = fetch(chrome.runtime.getURL(
let mandarinDict = await fetch(chrome.runtime.getURL(
"data/cedict_ts.u8")).then(r => r.text());
let cantoneseDict = fetch(chrome.runtime.getURL(
let cantoneseDict = await fetch(chrome.runtime.getURL(
"data/cedict_canto.u8")).then(r => r.text());
let grammarKeywords = fetch(chrome.runtime.getURL(
let grammarKeywords = await fetch(chrome.runtime.getURL(
"data/grammarKeywordsMin.json")).then(r => r.json());

return Promise.all([mandarinDict, cantoneseDict, grammarKeywords]);
return [mandarinDict, cantoneseDict, grammarKeywords]
}


async function loadDictionary() {
let [mandarinDict, cantoneseDict, grammarKeywords] = await loadDictData();
return new ZhongwenDictionary([{
dict = new ZhongwenDictionary([{
type: "common",
contents: mandarinDict
}, {
Expand All @@ -62,17 +66,32 @@ async function deactivateExtension() {
});

await chrome.storage.local.set({ "enabled": false })

const windows = chrome.windows.getAll(
{ 'populate': true }
);

for (let i = 0; i < windows.length; ++i) {
let tabs = windows[i].tabs;
for (let j = 0; j < tabs.length; ++j) {
chrome.tabs.sendMessage(tabs[j].id, {
'type': 'disable'
});
}
}

}

async function activateExtensionToggle() {
async function activateExtensionToggle(currentTab) {
const data = await chrome.storage.local.get(["enabled"])
console.log("Toggle")
if (data.enabled) {
await deactivateExtension();
} else {
await activateExtension();
await activateExtension(currentTab.id);
}
}


export { activateExtension, deactivateExtension, activateExtensionToggle, getDictionary, loadDictionary }
export { activateExtension, activateExtensionToggle, deactivateExtension, getDictionary, loadDictionary };

Loading

0 comments on commit ad80c69

Please sign in to comment.