Skip to content

Commit

Permalink
Added tests for json read
Browse files Browse the repository at this point in the history
  • Loading branch information
nbhoski committed May 24, 2024
1 parent 5eb9261 commit c0a4f7c
Showing 1 changed file with 50 additions and 4 deletions.
54 changes: 50 additions & 4 deletions src/buildSummary.unit.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
// Copyright 2024 The MathWorks, Inc.

import * as buildSummary from './buildSummary';
import * as fs from 'fs/promises';
import * as core from '@actions/core';
import { readFile } from 'fs';
import * as fs from 'fs';


jest.mock('@actions/core', () => ({
summary: {
Expand All @@ -13,8 +13,6 @@ jest.mock('@actions/core', () => ({
},
}));

const mockReadFile = readFile as jest.MockedFunction<typeof readFile>;

describe('summaryGeneration', () => {
it('generates a summary table correctly', () => {
const mockTasks = {
Expand Down Expand Up @@ -47,4 +45,52 @@ describe('summaryGeneration', () => {
expect(core.summary.addTable).toHaveBeenCalledTimes(1);
expect(core.summary.addTable).toHaveBeenCalledWith(mockTableRows);
});
});

jest.mock('fs/promises');

describe('readJsonFile', () => {
const mockReadFileAsync = fs.readFile as jest.MockedFunction<typeof fs.readFile>;

afterEach(() => {
jest.clearAllMocks();
});

it('reads and parses JSON file successfully', async () => {
const mockData: TaskList = {
taskDetails: [
{
name: 'Task 1',
description: 'Description 1',
failed: false,
skipped: false,
duration: '00:00:10',
},
],
};

mockReadFileAsync.mockResolvedValue(JSON.stringify(mockData));

const filePath = 'path/to/mockFile.json';
const result = await buildSummary.readJsonFile(filePath as string);

expect(mockReadFileAsync).toHaveBeenCalledWith(filePath, { encoding: 'utf8' });
expect(result).toEqual(mockData);
});

it('throws an error if the file cannot be read', async () => {
mockReadFileAsync.mockRejectedValue(new Error('File not found'));

const filePath = 'path/to/nonExistentFile.json';

await expect(buildSummary.readJsonFile(filePath as string)).rejects.toThrow('File not found');
});

it('throws an error if the file contains invalid JSON', async () => {
mockReadFileAsync.mockResolvedValue('invalid JSON');

const filePath = 'path/to/invalidJsonFile.json';

await expect(buildSummary.readJsonFile(filePath as string)).rejects.toThrow(SyntaxError);
});
});

0 comments on commit c0a4f7c

Please sign in to comment.