Reputation: 4290
I have the following code I am working with this API https://developer.mozilla.org/en-US/docs/Web/API/Performance/measureUserAgentSpecificMemory. The class is stripped right back
export class Memory {
private stopped = false
private isUserAgentSpecificMemorySupported = true
public memoryData: any = []
constructor() {}
public startMonitoring(): () => void {
if (this.isUserAgentSpecificMemorySupported) {
this.scheduleMeasurement()
}
return () => {
this.stopped = true
}
}
private async performMeasurement(): Promise<void> {
const memory = await (window.performance as any).measureUserAgentSpecificMemory()
const type = memory.breakdown.filter((e: any) => e.types.includes('JavaScript'))
this.memoryData.push(type[0].bytes)
}
}
Jest file.
import {Memory} from './memory'
type UserAgentSpecificMemoryBreakdown = {
bytes: number
types: Array<string>
}
type UserAgentSpecificMemory = {
bytes: number
breakdown: Array<UserAgentSpecificMemoryBreakdown>
}
type MockWindow = {
crossOriginIsolated?: boolean
performance: {
measureUserAgentSpecificMemory?: () => Promise<UserAgentSpecificMemory>
}
}
const data = {
bytes: 1500,
breakdown: [
{
bytes: 1000000,
types: ['JavaScript'],
},
{
bytes: 0,
types: ['DOM'],
},
],
}
describe('Test Memory Class', () => {
let mockWindow: MockWindow
let windowSpy: jest.SpyInstance
beforeEach(() => {
windowSpy = jest.spyOn(window, 'window', 'get')
mockWindow = {
...window,
performance: {
measureUserAgentSpecificMemory: jest.fn(() => Promise.resolve(data)),
},
}
windowSpy.mockImplementation(() => mockWindow)
})
afterEach(() => {
windowSpy.mockRestore()
})
it('should measure User Agent Specific Memory', async () => {
let memory = new Memory()
memory.startMonitoring()
expect(memory.memoryData).toEqual([1000000])
})
})
I am not sure how to make the test file await for the value in the test?
Any help would be great.
Upvotes: 0
Views: 127
Reputation: 16147
window
is an object and if it doesn’t contain window
function, you can not spy on it.
For your production code, just mock measureUserAgentSpecificMemory
function are enough:
import { Memory } from './memory'
describe('Memory', () => {
const data = {
bytes: 1500,
breakdown: [
{
bytes: 1000000,
types: ['JavaScript'],
},
{
bytes: 0,
types: ['DOM'],
},
],
};
let memory: Memory;
let measureUserAgentSpecificMemory: jest.Mock;
beforeEach(() => {
measureUserAgentSpecificMemory = jest.fn().mockResolvedValue(data);
(window as any).performance = {
measureUserAgentSpecificMemory,
};
memory = new Memory();
});
it('should measure User Agent Specific Memory', async () => {
memory.startMonitoring();
expect(memory.memoryData).toEqual([1000000]);
expect(measureUserAgentSpecificMemory).toHaveBeenCalled();
});
});
Upvotes: 1