cookie-dialog-monster/packages/browser-extension/tests/background/messages/database/refresh.test.ts

92 lines
2.8 KiB
TypeScript

import { beforeEach, describe, expect, it, jest } from '@jest/globals';
import handler from '~background/messages/database/refresh';
import { API_URL } from '~utils/constants';
import type { ExtensionData } from '~utils/types';
describe('background/messages/database/refresh.ts', () => {
const req = { name: 'database/refresh' as const };
const res = { send: jest.fn() };
beforeEach(() => {
jest.clearAllMocks();
});
it('should fetch data from the API, store it, and return the data when successful', async () => {
const data: ExtensionData = {
actions: [
{
domain: 'jestjs.io',
name: 'click',
selector: '#jest',
},
],
exclusions: {
domains: ['*.jestjs.io'],
overflows: ['*.jestjs.io'],
tags: ['JEST'],
},
keywords: ['jest'],
rules: [
{
action: {
type: 'block' as chrome.declarativeNetRequest.RuleActionType,
},
condition: {
resourceTypes: [
'font' as chrome.declarativeNetRequest.ResourceType,
'image' as chrome.declarativeNetRequest.ResourceType,
'media' as chrome.declarativeNetRequest.ResourceType,
'object' as chrome.declarativeNetRequest.ResourceType,
'script' as chrome.declarativeNetRequest.ResourceType,
'stylesheet' as chrome.declarativeNetRequest.ResourceType,
'xmlhttprequest' as chrome.declarativeNetRequest.ResourceType,
],
urlFilter: '||jestjs.io^',
},
id: 1,
priority: 1,
},
],
tokens: {
backdrops: ['#backdrop'],
classes: ['jest'],
containers: ['#container'],
selectors: ['#element'],
},
version: '0.0.0',
};
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
global.fetch = jest.fn(() =>
Promise.resolve({
json: () => Promise.resolve({ data, success: true }),
status: 200,
})
);
await handler(req, res);
expect(global.fetch).toHaveBeenCalledWith(`${API_URL}/data/`);
expect(chrome.storage.local.set).toHaveBeenCalledWith({ data });
expect(res.send).toHaveBeenCalledWith({ data, success: true });
});
it('should return success: false if the API call fails', async () => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
global.fetch = jest.fn(() =>
Promise.resolve({
json: () => Promise.resolve({ success: false }),
status: 200,
})
);
await handler(req, res);
expect(global.fetch).toHaveBeenCalledWith(`${API_URL}/data/`);
expect(chrome.storage.local.set).not.toHaveBeenCalled();
expect(res.send).toHaveBeenCalledWith({ success: false });
});
});