Skip to content

Testing: Improve Test Coverage for Fetch Operations #87

@AlexJSully

Description

@AlexJSully

Issue Description

Current test coverage for fetch operations is incomplete. The retrieveArticleData() function doesn't properly mock the Fetch API response, causing test errors and incomplete validation of the fetch-then-process chain.

Risk Level

MEDIUM

Affected Files

  • src/scripts/index.test.js
  • src/scripts/index.js (Lines 71-84 in retrieveArticleData())

Details

Current Test Issues

  1. Error in Tests: Tests produce console errors:

    Error retrieving article data: TypeError: response.json is not a function
    
  2. Incomplete Mock: The Fetch API response is not properly mocked in tests

  3. Gap in Coverage: Lines 77-78 (error path) are not properly validated

Current Code with Issue

fetch(articleDataUrl)
  .then((response) => response.json())  // Not mocked properly in tests
  .then((articleData) => {
    ArticleFiller.articleData = articleData;
    ArticleFiller.callArticle();
  })
  .catch((error) => {
    console.error("Error retrieving article data:", error);
  });

Expected Behavior

  1. All fetch operations should be properly mocked in tests
  2. Both success and error paths should be validated
  3. Test coverage for these lines should reach 100%

Solution Approach

Option A: Use jest-fetch-mock

npm install --save-dev jest-fetch-mock

Then in test setup:

import fetchMock from 'jest-fetch-mock';
fetchMock.enableMocks();

beforeEach(() => {
  fetchMock.resetMocks();
});

test('retrieveArticleData fetches and processes data', async () => {
  const mockData = { TestArticle: { title: 'Test' } };
  fetchMock.mockResponseOnce(JSON.stringify(mockData));
  
  ArticleFiller.retrieveArticleData();
  await new Promise(resolve => setTimeout(resolve, 10));
  
  expect(ArticleFiller.articleData).toEqual(mockData);
});

Option B: Manual Fetch Mock

global.fetch = jest.fn(() =>
  Promise.resolve({
    json: () => Promise.resolve({ TestArticle: {...} })
  })
);

Test Cases to Add

  1. ✅ Successfully fetch and parse article data
  2. ❌ Handle network errors
  3. ❌ Handle JSON parse errors
  4. ❌ Handle empty response
  5. ❌ Handle missing articleData.json file (404)

Current Coverage

  • Overall: 70.9%
  • Branch: 72.09%
  • Target: 85%+ with proper fetch mocking

Labels

testing, quality, coverage

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions