JSlang.dev

JavaScript Deep Dives with Wolfram. Since 2015
Inclusive, Test-Driven, Spec-Focused, Collaborative.

June 07, 2024
TestsSource
#jscc24 JSCraftCamp 2024 - TDD Session


Source Code

The source code we wrote during the event.

import {strict as assert} from 'assert';

const successfulStatus = [200, undefined];

const isSuccessful = ({responseStatus}) => successfulStatus.includes(responseStatus)
const isFailing = ({responseStatus}) => !isSuccessful({responseStatus});


function evaluateSuccessRatio(entries) {
  if (entries.length === 0) return 100;
  const successfulTests = entries.filter(isSuccessful).length;
  const failingTests = entries.filter(isFailing).length;
  return (successfulTests / (successfulTests+failingTests)) * 100;
}

describe('Evaluate the ratio of request successful/failing (ignoring unknown and missing response statuses)', function() {
  it('reports 100% successful requests when there no requests', function() {
    // Arrange
    const noRequests = [];
    // Act
    const actual = evaluateSuccessRatio(noRequests);
    // Assert
    const expected = 100;
    assert.equal(actual, expected);
  });

  describe('with one request only', () => {
    it('reports 100% successful, with missing response status', () => {
      const entry = {};
      const expected = 100;
      const oneRequestWithMissingResponseStatus = [entry];
      const actual = evaluateSuccessRatio(oneRequestWithMissingResponseStatus);
      assert.equal(actual, expected);
    });
    it('reports 0% successful, with response status 500', () => {
      const oneFailingRequest = [
        {responseStatus: 500}
      ];
      const actual = evaluateSuccessRatio(oneFailingRequest);
      const expected = 0;
      assert.equal(actual, expected);
    });
    it('reports 100% successful, with response status 200', () => {
      const oneSuccessfulRequest = [{responseStatus: 200}];
      const actual = evaluateSuccessRatio(oneSuccessfulRequest);
      let expected = 100;
      assert.equal(actual, expected);
    });
  });

  describe('with with many requests', () => {
    it('reports 100% successful, with all response status 200', () => {
      const requests = [
        {responseStatus: 200},
        {responseStatus: 200},
      ];
      const actual = evaluateSuccessRatio(requests);
      const expected = 100;
      assert.equal(actual, expected);
    });
    it('reports 0% successful, with all response status 404', () => {
      const requests = [
        {responseStatus: 404},
        {responseStatus: 404},
      ];
      const actual = evaluateSuccessRatio(requests);
      const expected = 0;
      assert.equal(actual, expected);
    });    
    it('reports 50% successful, with one response status 404 and one 200', () => {
      const requests = [
        {responseStatus: 404},
        {responseStatus: 200},
      ];
      const actual = evaluateSuccessRatio(requests);
      const expected = 50;
      assert.equal(actual, expected);
    });    
  });
});