diff --git a/extension/background.ts b/extension/background.ts index c99e249c6..dc19730c4 100644 --- a/extension/background.ts +++ b/extension/background.ts @@ -40,6 +40,10 @@ chrome.runtime.onMessage.addListener(async (request, sender, response) => { rcxMain.onTabSelect(sender.tab.id); break; case 'xsearch': + if (request.text === '') { + console.log('returning early due to empty string search'); + break; + } console.log('xsearch'); response(rcxMain.search(request.text, request.dictOption)); break; diff --git a/extension/test/background_test.ts b/extension/test/background_test.ts index 7e72d01c2..e0abd903e 100644 --- a/extension/test/background_test.ts +++ b/extension/test/background_test.ts @@ -66,24 +66,71 @@ describe('background.ts', function () { ); }); }); + describe('xsearch', function () { + it('should call response callback with search string and dictOptions value', async function () { + rcxMain.search = sinon + .stub() + .returns({ text: 'theText', dictOptions: '0' }); + const response = sinon.spy(); + + await sendMessageToBackground({ + tabId: 0, + type: 'xsearch', + text: 'A non empty string', + responseCallback: response, + }); + + expect(response).to.have.been.calledWithMatch({ + text: 'theText', + dictOptions: sinon.match.any, + }); + expect(response).to.have.been.calledOnce; + }); + + it('should not search if request.text is an empty string', async function () { + const response = sinon.spy(); + + await sendMessageToBackground({ + tabId: 0, + type: 'xsearch', + text: '', + responseCallback: response, + }); + + expect(response.called).to.be.false; + }); + }); }); +type Payload = { + tabId?: number; + text?: string; + type: string; + responseCallback?: (response: unknown) => void; +}; + async function sendMessageToBackground({ tabId = 0, type, + text, responseCallback = () => { // Do nothing by default. }, -}: { - tabId?: number; - type: string; - responseCallback?: (response: unknown) => void; -}): Promise { +}: Payload): Promise { + const request: { type: string; text?: string } = { + type, + }; + const sender = { + tab: { id: tabId }, + }; + if (text !== undefined) { + request['text'] = text; + } // In background.ts, a promise is passed to `addListener` so we can await it here. // eslint-disable-next-line @typescript-eslint/await-thenable await chrome.runtime.onMessage.addListener.yield( - { type: type }, - { tab: { id: tabId } }, + request, + sender, responseCallback ); return;