Вы должны проверить и убедиться, что логика функции formatBitrate
правильная. Затем вы можете проверить логику функции mapStateToProps
.
Например,
index.ts
:
export const formatBitrate = bitrate => {
if (bitrate === 0) {
return '0 Bytes';
}
const k = 1024;
const sizes = ['Bytes', 'kbps', 'mbps', 'gbps', 'tbps', 'pbps', 'ebps', 'zbps', 'ybps'];
const i = Math.floor(Math.log(bitrate) / Math.log(k));
return `${parseFloat((bitrate / k ** i).toFixed(0))}\u00A0${sizes[i]}`;
};
export const mapStateToProps = state => {
let plotData = state.qualityResults.plotData;
const lastTimestamp = Number(Object.keys(plotData)[0]);
plotData = Object.keys(plotData).map(key => ({
timestamp: Number(key),
bytesReceived: plotData[key].bytesReceived,
seconds: `${Math.ceil(Math.abs(Number(key) - lastTimestamp) / 1000)}s`
}));
return {
plotData,
mos: Number(state.qualityResults.video.mos).toFixed(1),
packetLossRatio: Number(state.qualityResults.video.packetLossRatio).toFixed(0),
bitrate: formatBitrate(state.qualityResults.video.bitrate)
};
};
index.spec.ts
:
import { formatBitrate, mapStateToProps } from './';
describe('formatBitrate', () => {
test('should format bitrate', () => {
const actualValue = formatBitrate(1024);
expect(actualValue).toBe('1\u00A0kbps');
});
test('should return 0 Bytes', () => {
const actualValue = formatBitrate(0);
expect(actualValue).toBe('0 Bytes');
});
});
describe('mapStateToProps', () => {
test('should return mapped state', () => {
const mState = {
qualityResults: {
video: {
mos: 2,
packetLossRatio: 1,
bitrate: 1024
},
plotData: {
2333333: {
bytesReceived: 666
}
}
}
};
const actualValue = mapStateToProps(mState);
expect(actualValue).toEqual({
plotData: [{ timestamp: 2333333, bytesReceived: 666, seconds: '0s' }],
mos: '2.0',
packetLossRatio: '1',
bitrate: '1\u00A0kbps'
});
});
});
Результат модульного теста со 100% покрытием:
PASS src/stackoverflow/58775089/index.spec.ts (7.933s)
formatBitrate
✓ should format bitrate (4ms)
✓ should return 0 Bytes (1ms)
mapStateToProps
✓ should return mapped state (2ms)
----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.ts | 100 | 100 | 100 | 100 | |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 3 passed, 3 total
Snapshots: 0 total
Time: 9.301s, estimated 11s
Исходный код: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58775089