skip to Main Content
module.exports.get = function(req, url, callback, errorCallback) {
  https.get(getOptions(req, url), (response) => {
    handleResponse(response, callback, errorCallback);
  }).on('error', (e) => {
    console.error('MYAPP-GET Request.', e);
    if (errorCallback) {
      errorCallback(e);
    }
  });
};


function handleResponse(response, callback, errorCallback) {
  let rawData = '';
  response.on('data', (chunk) => {
    rawData += chunk;
  });

  response.on('end', () => {
    if (response.statusCode >= 200 && response.statusCode < 300) {
      callback(checkJSONResponse(rawData));
    } else if (errorCallback) {
      errorCallback(rawData);
    }
  });

}

function checkJSONResponse(rawData) {
  if (typeof rawData === 'object') {
    return rawData;
  }

  let data = {};
  if (rawData.length > 0) {
    try {
      data = JSON.parse(rawData);
    } catch (e) {
      console.log('Response is not JSON.');
      if (e) {
        console.log(e);
      }
      data = {};
    }
  }

  return data;
}

I am learning more about writing JUnit test cases for apps written in Javascript.

Below is what I have so far. I know it is not correct. Need help writing code to cover the above. If there are any good links to learn more about JUnit test cases please place them also in the reply. Thank You.

describe('>>> CRUD tests', () => {
  it('+++ test > get method', () => {
    
    const getSpy = jest.spyOn(crud, 'get');
    const httpAPISpy = jest.spyOn(http, 'get');
    getSpy.mockReturnValue(httpAPISpy.mockReturnValue());
    expect(getSpy).toHaveBeenCalledTimes(1);
  });
});

2

Answers


  1. Chosen as BEST ANSWER

    // Test 1: Get a successful response from a valid URL
    describe("get", () => {
      it("should get a successful response from a valid URL", async () => {
        const url = "https://www.google.com";
        const expectedStatusCode = 200;
        const expectedData = {
          name: "Google",
          domain: "www.google.com",
        };
    
        const response = await module.exports.get(null, url, (data) => {
          expect(data).toEqual(expectedData);
        });
    
        expect(response.statusCode).toEqual(expectedStatusCode);
      });
    });
    
    // Test 2: Get an error response from an invalid URL
    describe("get", () => {
      it("should get an error response from an invalid URL", async () => {
        const url = "https://www.google.com/asdfasdf";
        const expectedStatusCode = 404;
        const expectedData = null;
    
        const response = await module.exports.get(null, url, (data) => {
          expect(data).toEqual(expectedData);
        });
    
        expect(response.statusCode).toEqual(expectedStatusCode);
      });
    });
    
    // Test 3: Get a JSON response
    describe("get", () => {
      it("should get a JSON response", async () => {
        const url = "https://api.github.com/users/bard";
        const expectedStatusCode = 200;
        const expectedData = {
          login: "bard",
          name: "Bard",
          email: "[email protected]",
        };
    
        const response = await module.exports.get(null, url, (data) => {
          expect(data).toEqual(expectedData);
        });
    
        expect(response.statusCode).toEqual(expectedStatusCode);
      });
    });


  2. // Import the module and the dependencies
    const { get } = require('./your-module.js');
    const https = require('https');
    
    // Use a mock server to test the requests
    const nock = require('nock');
    
    // Define some test data
    const testUrl = 'https://example.com/api';
    const testReq = { headers: { 'User-Agent': 'test' } };
    const testRes = { message: 'success' };
    const testErr = { message: 'error' };
    
    // Define a helper function to mock the https.get method
    function mockGet(options, response) {
      nock('https://example.com')
        .get(options.path)
        .reply(response.statusCode, response.body);
    }
    
    // Define the test suite
    describe('get', () => {
      // Test the happy path
      test('should call the callback with the parsed JSON response', (done) => {
        // Mock the https.get method with a 200 status code and a JSON body
        mockGet(getOptions(testReq, testUrl), { statusCode: 200, body: testRes });
    
        // Call the get function with the test parameters
        get(testReq, testUrl, (data) => {
          // Expect the data to be equal to the test response
          expect(data).toEqual(testRes);
          // End the test
          done();
        }, (error) => {
          // Fail the test if the error callback is called
          done(error);
        });
      });
    
      // Test the error path
      test('should call the error callback with the raw response', (done) => {
        // Mock the https.get method with a 400 status code and a non-JSON body
        mockGet(getOptions(testReq, testUrl), { statusCode: 400, body: 'Not Found' });
    
        // Call the get function with the test parameters
        get(testReq, testUrl, (data) => {
          // Fail the test if the callback is called
          done(new Error('Callback should not be called'));
        }, (error) => {
          // Expect the error to be equal to the test error
          expect(error).toBe('Not Found');
          // End the test
          done();
        });
      });
    
      // Test the exception path
      test('should call the error callback with the error object', (done) => {
        // Mock the https.get method with an error event
        mockGet(getOptions(testReq, testUrl), new Error('Network Error'));
    
        // Call the get function with the test parameters
        get(testReq, testUrl, (data) => {
          // Fail the test if the callback is called
          done(new Error('Callback should not be called'));
        }, (error) => {
          // Expect the error to have a message property
          expect(error).toHaveProperty('message');
          // End the test
          done();
        });
      });
    });
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search