如何使用Jest测试两个不同的JavaScript函数?
Hey there! As someone new to testing in this space, I totally get wanting clear, actionable steps to test these functions with Jest. Let's break this down into two parts—testing the formatBitrate converter first, then moving on to mapStateToProps. I'll include concrete test cases and explanations so you can follow along easily.
formatBitrate Function First, let's recap what this function does:
- Returns
'0 Bytes'when the input is 0 - Converts a raw bitrate value into a human-readable format using 1024-based units (Bytes → kbps → mbps, etc.)
- Rounds the converted value to an integer via
toFixed(0)
We need to test all key scenarios to ensure it behaves as expected. Here's how to structure your test file:
// Import your formatBitrate function here (adjust the path to match your project structure) const { formatBitrate } = require('./your-file-path'); describe('formatBitrate', () => { test('returns "0 Bytes" when bitrate is 0', () => { expect(formatBitrate(0)).toBe('0 Bytes'); }); test('returns correct Bytes format for values under 1024', () => { expect(formatBitrate(512)).toBe('512 Bytes'); expect(formatBitrate(1023)).toBe('1023 Bytes'); }); test('converts to kbps for values equal to or over 1024', () => { expect(formatBitrate(1024)).toBe('1 kbps'); expect(formatBitrate(2048)).toBe('2 kbps'); expect(formatBitrate(1500)).toBe('1 kbps'); // 1500/1024 ≈1.46 → rounded to 1 }); test('converts to mbps, gbps, etc., for larger values', () => { expect(formatBitrate(1024 ** 2)).toBe('1 mbps'); // 1048576 expect(formatBitrate(1024 ** 3)).toBe('1 gbps'); expect(formatBitrate(1024 ** 4)).toBe('1 tbps'); }); });
Each test targets a specific edge case or common scenario, ensuring the function handles all expected inputs correctly.
mapStateToProps Function This is a Redux mapStateToProps function—it takes a Redux state and returns a props object. It depends on formatBitrate and processes the plotData structure. To test this properly, we'll:
- Isolate the function from external dependencies by mocking
formatBitrate - Create a mock Redux state that matches the structure the function expects
- Assert that the returned props match our expectations
Here's the test code:
// Import your mapStateToProps and formatBitrate functions const { mapStateToProps, formatBitrate } = require('./your-file-path'); // Mock the formatBitrate function to control its return value (isolates our test) jest.mock('./your-file-path', () => ({ ...jest.requireActual('./your-file-path'), formatBitrate: jest.fn() })); describe('mapStateToProps', () => { beforeEach(() => { // Reset the mock before each test to avoid cross-test contamination formatBitrate.mockReset(); }); test('transforms plotData correctly and returns expected props', () => { // Create a mock state with sample data const mockState = { qualityResults: { plotData: { '1620000000000': { bytesReceived: 1000 }, '1620000003000': { bytesReceived: 2500 }, '1620000005000': { bytesReceived: 4000 } }, video: { mos: 3.75, packetLossRatio: 2.8, bitrate: 2048 } } }; // Set up the mock for formatBitrate formatBitrate.mockReturnValue('2 kbps'); // Call mapStateToProps with our mock state const result = mapStateToProps(mockState); // Assert plotData is transformed correctly expect(result.plotData).toEqual([ { timestamp: 1620000000000, bytesReceived: 1000, seconds: '0s' // Difference from lastTimestamp (itself) is 0 → ceil(0) =0 }, { timestamp: 1620000003000, bytesReceived: 2500, seconds: '3s' // (3000ms /1000) =3 → ceil(3)=3 }, { timestamp: 1620000005000, bytesReceived: 4000, seconds: '5s' // (5000ms /1000)=5 → ceil(5)=5 } ]); // Assert other props are formatted correctly expect(result.mos).toBe('3.8'); // 3.75 rounded to 1 decimal place expect(result.packetLossRatio).toBe('3'); // 2.8 rounded to 0 decimals expect(result.bitrate).toBe('2 kbps'); // Matches our mock return value expect(formatBitrate).toHaveBeenCalledWith(2048); // Verify it was called with the right bitrate }); test('handles empty plotData gracefully (optional edge case)', () => { const mockState = { qualityResults: { plotData: {}, video: { mos: 4.0, packetLossRatio: 0, bitrate: 0 } } }; formatBitrate.mockReturnValue('0 Bytes'); const result = mapStateToProps(mockState); expect(result.plotData).toEqual([]); // Empty array since no keys to map expect(result.mos).toBe('4.0'); expect(result.packetLossRatio).toBe('0'); expect(result.bitrate).toBe('0 Bytes'); }); });
Key Notes for mapStateToProps Tests:
- We use
jest.mockto overrideformatBitratewith a mock function. This lets us testmapStateToPropsin isolation without relying on whetherformatBitrateworks (we already tested that separately!). - The
beforeEachhook resets the mock so each test starts fresh. - We test an edge case (empty
plotData) to ensure the function doesn't crash when there's no data.
That's it! These tests cover the core functionality of both functions. You can add more edge cases if needed (like negative bitrates, though your current function might not handle those—feel free to extend the tests if you add that logic later).
内容的提问来源于stack exchange,提问作者thodwris

