Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions voter/src/040d2c710c.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Test generated by RoostGPT for test zb-js-test using AI Type Open AI and AI Model gpt-4

import React from 'react';
import { shallow } from 'enzyme';
import Home from './Home';

describe('Home component', () => {
let wrapper;
let instance;

beforeAll(() => {
jest.useFakeTimers();
wrapper = shallow(<Home />);
instance = wrapper.instance();
});

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

test('should clear timeout on unmount', () => {
instance.componentWillUnmount();
expect(clearTimeout).toHaveBeenCalledWith(instance.timer);
});

test('should not clear timeout if timer is not set', () => {
instance.timer = null;
instance.componentWillUnmount();
expect(clearTimeout).not.toHaveBeenCalled();
});
});
55 changes: 55 additions & 0 deletions voter/src/4cbc3930cb.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// Test generated by RoostGPT for test zb-js-test using AI Type Open AI and AI Model gpt-4

import React from 'react';
import { shallow } from 'enzyme';
import Result from './Result';

jest.mock('node-fetch', () => require('fetch-mock-jest').sandbox());

const fetchMock = require('node-fetch');

describe('Result component', () => {
let component;
const ballot_endpoint = '//localhost:3000/ballot';
const ec_server_endpoint = '//localhost:3000/ec-server';

beforeEach(() => {
component = shallow(<Result />);
fetchMock.restore();
});

it('should fetch results on componentDidMount', async () => {
fetchMock.get(`http:${ballot_endpoint}`, {
results: ['result1', 'result2'],
total_votes: 100,
});

await component.instance().componentDidMount();
expect(component.state('results')).toEqual(['result1', 'result2']);
expect(component.state('total_votes')).toBe(100);
});

it('should handle error on fetching results', async () => {
fetchMock.get(`http:${ballot_endpoint}`, 500);

await component.instance().componentDidMount();
expect(component.state('results')).toEqual([]);
expect(component.state('total_votes')).toBe(0);
});

it('should fetch candidates on componentDidMount', async () => {
fetchMock.get(`http:${ec_server_endpoint}`, {
Candidates: ['candidate1', 'candidate2'],
});

await component.instance().componentDidMount();
expect(component.state('candidates')).toEqual(['candidate1', 'candidate2']);
});

it('should handle error on fetching candidates', async () => {
fetchMock.get(`http:${ec_server_endpoint}`, 500);

await component.instance().componentDidMount();
expect(component.state('candidates')).toEqual([]);
});
});
52 changes: 52 additions & 0 deletions voter/src/508b7d38f7.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// Test generated by RoostGPT for test zb-js-test using AI Type Open AI and AI Model gpt-4

import React from 'react';
import { shallow } from 'enzyme';
import Home from './Home';

describe('Home Component', () => {
let wrapper;
let mockFetch;

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

wrapper = shallow(<Home />);
});

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

test('should update state when candidate_id changes', () => {
wrapper.setState({ candidate_id: '1', voter_id: '1' });
wrapper.instance().componentDidUpdate({ candidate_id: '2' }, {});

expect(mockFetch).toHaveBeenCalled();
expect(mockFetch.mock.calls[0][0]).toContain('http:');
expect(mockFetch.mock.calls[0][1].method).toEqual('POST');
expect(JSON.parse(mockFetch.mock.calls[0][1].body)).toEqual({ candidate_id: '1', vote: '1' });
});

test('should not make a fetch call when ballot_endpoint is empty', () => {
wrapper.setState({ candidate_id: '1', voter_id: '1' });
global.ballot_endpoint = '';

wrapper.instance().componentDidUpdate({ candidate_id: '2' }, {});

expect(mockFetch).not.toHaveBeenCalled();
});

test('should update state when showResultsButton changes', () => {
jest.useFakeTimers();
wrapper.setState({ showResultsButton: true });

wrapper.instance().componentDidUpdate({ showResultsButton: false }, {});

expect(setTimeout).toHaveBeenCalledTimes(1);
expect(setTimeout).toHaveBeenLastCalledWith(expect.any(Function), 3000);
});
});
29 changes: 29 additions & 0 deletions voter/src/9023d0a7be.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Test generated by RoostGPT for test zb-js-test using AI Type Open AI and AI Model gpt-4

import React from 'react';
import { shallow } from 'enzyme';
import Result from './Result';

describe('Result component', () => {
let component;

beforeEach(() => {
component = shallow(<Result />);
});

afterEach(() => {
component.unmount();
});

it('should have correct initial state', () => {
expect(component.state()).toEqual({
candidates: [],
results: [],
total_votes: 0,
});
});

it('state should not be null', () => {
expect(component.state()).not.toBeNull();
});
});
38 changes: 38 additions & 0 deletions voter/src/App_94baa27ecc.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// Test generated by RoostGPT for test zb-js-test using AI Type Open AI and AI Model gpt-4

import React from "react";
import { render, screen } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import App from './App';

describe('App', () => {
test('renders Home component when at /', () => {
render(
<MemoryRouter initialEntries={['/']}>
<App />
</MemoryRouter>
);

expect(screen.getByText('Home')).toBeInTheDocument();
});

test('renders Result component when at /result', () => {
render(
<MemoryRouter initialEntries={['/result']}>
<App />
</MemoryRouter>
);

expect(screen.getByText('Result')).toBeInTheDocument();
});

test('redirects to / when visiting non-existing routes', () => {
render(
<MemoryRouter initialEntries={['/non-existing-route']}>
<App />
</MemoryRouter>
);

expect(screen.getByText('Home')).toBeInTheDocument();
});
});
54 changes: 54 additions & 0 deletions voter/src/CustomCard_4a8d7ba2ca.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// Test generated by RoostGPT for test zb-js-test using AI Type Open AI and AI Model gpt-4

import React from 'react';
import { shallow } from 'enzyme';
import Result from './Result';

describe('Result Component', () => {
let wrapper;
let instance;

const mockState = {
results: [
{ candidate_id: 'docker', vote_count: 5 },
{ candidate_id: 'minikube', vote_count: 3 }
],
candidates: [
{ Name: 'docker', ImageUrl: 'docker.png' },
{ Name: 'minikube', ImageUrl: 'minikube.png' }
],
total_votes: 8
};

beforeEach(() => {
wrapper = shallow(<Result />);
instance = wrapper.instance();
instance.setState(mockState);
});

test('should render without throwing an error', () => {
expect(wrapper.exists()).toBe(true);
});

test('should render correct number of custom cards', () => {
expect(wrapper.find('.card').length).toBe(mockState.results.length);
});

test('should render no votes message when no results', () => {
instance.setState({ results: [] });
expect(wrapper.find('.heading').text()).toBe('No votes has been given');
});

test('should render candidate image correctly', () => {
const firstCard = wrapper.find('.card').at(0);
expect(firstCard.find('img').prop('src')).toBe('docker.png');
});

test('should render progress bar correctly', () => {
const firstCard = wrapper.find('.card').at(0);
const progress = Math.round(
(mockState.results[0].vote_count / mockState.total_votes) * 100
);
expect(firstCard.find('.progressbar_front').prop('style')).toHaveProperty('width', `${progress}%`);
});
});
38 changes: 38 additions & 0 deletions voter/src/CustomCard_9d6be392ee.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// Test generated by RoostGPT for test zb-js-test using AI Type Open AI and AI Model gpt-4

import React from 'react';
import { shallow } from 'enzyme';
import CustomCard from './Result';

describe('CustomCard', () => {
let wrapper;
let candidate = { candidate_id: 'docker', vote_count: 50 };
let total_votes = 100;

beforeEach(() => {
wrapper = shallow(<CustomCard candidate={candidate} total_votes={total_votes} />);
});

test('renders the card correctly', () => {
expect(wrapper.find('.card')).toHaveLength(1);
});

test('renders the correct candidate id', () => {
expect(wrapper.find('.cardContent').text()).toContain(candidate.candidate_id);
});

test('calculates the correct vote percentage', () => {
const votePercentage = Math.round((candidate.vote_count / total_votes) * 100);
expect(wrapper.find('.progressbar_front').prop('style')).toHaveProperty('width', `${votePercentage}%`);
expect(wrapper.find('.progressbar_back div').text()).toBe(`${votePercentage}%`);
});

test('renders the correct image for the candidate', () => {
expect(wrapper.find('.cardBackgroundImage img').prop('src')).toBe(docker);
});

test('does not render an image if the candidate id does not match', () => {
wrapper.setProps({ candidate: { candidate_id: 'unknown', vote_count: 50 } });
expect(wrapper.find('.cardBackgroundImage img')).toHaveLength(0);
});
});
52 changes: 52 additions & 0 deletions voter/src/checkValidServiceWorker_294ace5fce.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// Test generated by RoostGPT for test zb-js-test using AI Type Open AI and AI Model gpt-4

jest.mock('node-fetch');
const fetch = require('node-fetch');
const {Response} = jest.requireActual('node-fetch');

const { checkValidServiceWorker, registerValidSW } = require('./serviceWorker');

describe('Service Worker Testing', () => {

beforeEach(() => {
fetch.mockClear();
});

test('should find valid service worker and register it', async () => {
fetch.mockReturnValue(
Promise.resolve(
new Response(JSON.stringify({}), { headers: { 'content-type': 'application/javascript' } })
)
);

const mockRegisterValidSW = jest.fn();
registerValidSW = mockRegisterValidSW;

await checkValidServiceWorker('swUrl', {});
expect(mockRegisterValidSW).toHaveBeenCalled();
});

test('should not find service worker and reload the page', async () => {
fetch.mockReturnValue(
Promise.resolve(
new Response(JSON.stringify({}), { status: 404 })
)
);

const mockReload = jest.fn();
global.window.location.reload = mockReload;

await checkValidServiceWorker('swUrl', {});
expect(mockReload).toHaveBeenCalled();
});

test('should handle when fetch fails', async () => {
fetch.mockReturnValue(Promise.reject('API is down'));

const consoleSpy = jest.spyOn(console, 'log');

await checkValidServiceWorker('swUrl', {});
expect(consoleSpy).toHaveBeenCalledWith('No internet connection found. App is running in offline mode.');
});

});
8 changes: 8 additions & 0 deletions voter/src/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module.exports = {
testEnvironment: 'node',
testRegex: '(/__tests__/.*|(\.|/)(test|spec))\.(jsx?|tsx?)$',
moduleFileExtensions: ['js', 'jsx', 'ts', 'tsx'],
transform: {
'^.+\.(jsx?|tsx?)$': 'babel-jest',
},
};
Loading