test: fix unit tests for WebExtension build

This commit is contained in:
xenticore
2025-05-01 18:26:05 -04:00
parent 745087a1cb
commit 91f43295e8
3 changed files with 38 additions and 30 deletions

View File

@@ -57,7 +57,7 @@ describe('prepareExchangeRates', () => {
const rates = await prepareExchangeRates(); const rates = await prepareExchangeRates();
expect(rates).toEqual(mockRates); expect(rates).toEqual(mockRates);
expect(GM_fetch).not.toHaveBeenCalled(); expect(GM_fetch as jest.Mock).not.toHaveBeenCalled();
}); });
it('should fetch new rates when they are expired', async () => { it('should fetch new rates when they are expired', async () => {
@@ -66,17 +66,18 @@ describe('prepareExchangeRates', () => {
if (key === storage_exchangerates_next) return new Date(Date.now() - 50000).toISOString(); if (key === storage_exchangerates_next) return new Date(Date.now() - 50000).toISOString();
return null; return null;
}); });
const mockResponse = {
rates: mockRates,
time_next_update_utc: new Date(Date.now() + 100000).toISOString()
};
(GM_fetch as jest.Mock).mockResolvedValue({ (GM_fetch as jest.Mock).mockResolvedValue({
ok: true, ok: true,
json: async () => ({ json: async () => (mockResponse)
rates: mockRates,
time_next_update_utc: new Date(Date.now() + 100000).toISOString()
})
}); });
(chrome.runtime.sendMessage as jest.Fn).mockImplementation(() => mockResponse);
const rates = await prepareExchangeRates(); const rates = await prepareExchangeRates();
expect(rates).toEqual(mockRates); expect(rates).toEqual(mockRates);
expect(GM_fetch).toHaveBeenCalled();
expect(setStorageValue).toHaveBeenCalledWith(storage_exchangerates, mockRates); expect(setStorageValue).toHaveBeenCalledWith(storage_exchangerates, mockRates);
}); });
@@ -86,6 +87,7 @@ describe('prepareExchangeRates', () => {
ok: false, ok: false,
status: 500 status: 500
} as Response); } as Response);
(chrome.runtime.sendMessage as jest.Fn).mockImplementation(() => {});
const rates = await prepareExchangeRates(); const rates = await prepareExchangeRates();
expect(rates).toBeNull(); expect(rates).toBeNull();

View File

@@ -58,11 +58,11 @@ describe('Price Service', () => {
test('fetchPrice fetches new data when cache is expired', async () => { test('fetchPrice fetches new data when cache is expired', async () => {
const expiredCache: ItemPriceData = { ...mockCachedData, update: new Date(Date.now() - 2 * mockTtl).getTime() }; const expiredCache: ItemPriceData = { ...mockCachedData, update: new Date(Date.now() - 2 * mockTtl).getTime() };
(getStorageValue as jest.Mock).mockResolvedValue(expiredCache); (getStorageValue as jest.Mock).mockResolvedValue(expiredCache);
(priceUsingPricesTF as jest.Mock).mockResolvedValue(mockPriceResponse) (priceUsingPricesTF as jest.Mock).mockResolvedValue(mockPriceResponse);
(chrome.runtime.sendMessage as jest.Fn).mockImplementation(() => mockPriceResponse);
const result = await fetchPrice(mockToken, mockDefIndex + ";" + mockQuality) const result = await fetchPrice(mockToken, mockDefIndex + ";" + mockQuality)
expect(priceUsingPricesTF).toHaveBeenCalledWith(mockToken, `${mockDefIndex};${mockQuality}`)
expect(setStorageValue).toHaveBeenCalled() expect(setStorageValue).toHaveBeenCalled()
expect(result.metal).not.toBe(mockCachedData.metal) expect(result.metal).not.toBe(mockCachedData.metal)
expect(result.metal).toBe(mockPriceResponse.metal) expect(result.metal).toBe(mockPriceResponse.metal)
@@ -73,8 +73,8 @@ describe('Price Service', () => {
}) })
test('fetchPrice handles pricing API errors', async () => { test('fetchPrice handles pricing API errors', async () => {
const testError = 500; (chrome.runtime.sendMessage as jest.Fn).mockResolvedValue(null);
(priceUsingPricesTF as jest.Mock).mockRejectedValue(testError); (priceUsingPricesTF as jest.Mock).mockImplementation(() => Promise.reject(new Error('500 Internal Server Error')));
(getStorageValue as jest.Mock).mockResolvedValue(null) (getStorageValue as jest.Mock).mockResolvedValue(null)
await expect(fetchPrice(mockToken, mockDefIndex + ";" + mockQuality)).rejects.toThrow() await expect(fetchPrice(mockToken, mockDefIndex + ";" + mockQuality)).rejects.toThrow()
@@ -82,11 +82,11 @@ describe('Price Service', () => {
test('fetchKeyPrice uses correct parameters', async () => { test('fetchKeyPrice uses correct parameters', async () => {
(getStorageValue as jest.Mock).mockResolvedValue(null); (getStorageValue as jest.Mock).mockResolvedValue(null);
(priceUsingPricesTF as jest.Mock).mockResolvedValue(mockKeyPriceResponse) (priceUsingPricesTF as jest.Mock).mockResolvedValue(mockKeyPriceResponse);
(chrome.runtime.sendMessage as jest.Fn).mockImplementation(() => mockKeyPriceResponse);
const result = await fetchKeyPrice(mockToken) const result = await fetchKeyPrice(mockToken)
expect(priceUsingPricesTF).toHaveBeenCalledWith(mockToken, `${defindex_key};6`)
expect(result.keys).toBe(0) // A key cannot cost a key :P expect(result.keys).toBe(0) // A key cannot cost a key :P
expect(result.metal).toBe(mockKeyPriceResponse.metal) expect(result.metal).toBe(mockKeyPriceResponse.metal)
}) })

View File

@@ -1,4 +1,4 @@
import { describe, expect, test, mock } from "bun:test"; import { describe, expect, test, mock, beforeEach, jest } from "bun:test";
import { ItemSchema, ItemSlot, getItemIndexByName, getTradableStatusByDefindex, getTradableStatusByName, linkBotkillerVariants, linkFestiveVariants, prepareSchema } from '../src/content/schemaService' import { ItemSchema, ItemSlot, getItemIndexByName, getTradableStatusByDefindex, getTradableStatusByName, linkBotkillerVariants, linkFestiveVariants, prepareSchema } from '../src/content/schemaService'
// Mock the storage and log functions // Mock the storage and log functions
@@ -13,6 +13,24 @@ mock.module('../src/content/utils/log', () => ({
logError: mock(() => {}) logError: mock(() => {})
})); }));
const mockSchemaResponse = [
{
defindex: 1,
item_name: 'Test Item',
item_slot: 'misc',
attributes: [
{ "name": "cannot trade", "class": "cannot_trade", "value": 1 }
],
capabilities: {}
},
{
defindex: 208,
item_name: 'Flame Thrower',
item_slot: 'primary',
capabilities: { can_killstreakify: true }
}
]
const mockSchema: ItemSchema = { const mockSchema: ItemSchema = {
'21': { '21': {
name: 'Flame Thrower', name: 'Flame Thrower',
@@ -89,6 +107,7 @@ const mockSchema: ItemSchema = {
} }
describe('Schema Service', () => { describe('Schema Service', () => {
test('getItemIndexByName returns correct defindex', () => { test('getItemIndexByName returns correct defindex', () => {
expect(getItemIndexByName(mockSchema, 'Flame Thrower')).toBe(208) expect(getItemIndexByName(mockSchema, 'Flame Thrower')).toBe(208)
expect(getItemIndexByName(mockSchema, 'Mann Co. Supply Crate Key')).toBe(5021) expect(getItemIndexByName(mockSchema, 'Mann Co. Supply Crate Key')).toBe(5021)
@@ -113,25 +132,12 @@ describe('Schema Service', () => {
// Mock GM_fetch response // Mock GM_fetch response
const mockResponse = { const mockResponse = {
ok: true, ok: true,
json: async () => [ json: async () => mockSchemaResponse
{
defindex: 1,
item_name: 'Test Item',
item_slot: 'misc',
attributes: [
{ "name": "cannot trade", "class": "cannot_trade", "value": 1 }
],
capabilities: {}
},
{
defindex: 208,
item_name: 'Flame Thrower',
item_slot: 'primary',
capabilities: { can_killstreakify: true }
}
]
}; };
// Mock Chrome runtime message
(chrome.runtime.sendMessage as jest.Fn).mockImplementation(() => mockSchemaResponse);
// Mock GM_fetch // Mock GM_fetch
globalThis.GM_fetch = mock(async () => mockResponse); globalThis.GM_fetch = mock(async () => mockResponse);