Skip to content

Commit

Permalink
added test cases for point distance, region tags and settings provider
Browse files Browse the repository at this point in the history
  • Loading branch information
sumn2u committed Jun 15, 2024
1 parent c9b736a commit 668a6c9
Show file tree
Hide file tree
Showing 5 changed files with 201 additions and 1 deletion.
41 changes: 41 additions & 0 deletions client/src/PointDistances/PointDistances.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import React from 'react'
import { render } from '@testing-library/react'
import '@testing-library/jest-dom'
import PointDistances from './index'

const mockProjectRegionBox = jest.fn(region => ({
...region,
w: 10,
h: 10,
}))

describe('PointDistances component', () => {
it('renders correctly and displays distances', () => {
const regions = [
{ id: 1, type: 'point', x: 0.1, y: 0.2 },
{ id: 2, type: 'point', x: 0.4, y: 0.6 },
]
const pointDistancePrecision = 2
const realSize = { w: 100, h: 100, unitName: 'cm' }

const { container, getByText } = render(
<PointDistances
projectRegionBox={mockProjectRegionBox}
regions={regions}
pointDistancePrecision={pointDistancePrecision}
realSize={realSize}
/>
)

// Check if path element is rendered
expect(container.querySelector('path')).toBeInTheDocument()

// Check if text element is rendered with correct distance
const expectedDistance = Math.sqrt(
Math.pow(regions[0].x * realSize.w - regions[1].x * realSize.w, 2) +
Math.pow(regions[0].y * realSize.h - regions[1].y * realSize.h, 2)
).toFixed(pointDistancePrecision) + realSize.unitName

expect(getByText(expectedDistance)).toBeInTheDocument()
})
})
85 changes: 85 additions & 0 deletions client/src/RegionTags/RegionTags.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import React from 'react'
import { render } from '@testing-library/react'
import '@testing-library/jest-dom'
import RegionTags from './index'

const mockProjectRegionBox = jest.fn(region => ({
x: region.x * 100,
y: region.y * 100,
w: region.w * 100,
h: region.h * 100,
}))

const mouseEvents = {
onMouseDown: jest.fn(),
onMouseUp: jest.fn(),
onMouseMove: jest.fn(),
}

const regionClsList = ['Class1', 'Class2']
const regionTagList = ['Tag1', 'Tag2']
const onBeginRegionEdit = jest.fn()
const onChangeRegion = jest.fn()
const onCloseRegionEdit = jest.fn()
const onDeleteRegion = jest.fn()
const onRegionClassAdded = jest.fn()
const enabledRegionProps = ['tags']
const imageSrc = 'test-image.jpg'
const layoutParams = { current: { iw: 800, ih: 600 } }


// Mock the useTranslation hook
jest.mock('react-i18next', () => ({
useTranslation: () => ({
t: key => ({
"configuration.image_upload.description": "Upload images",
"error.server_connection": "Server connection error",
}[key]),
}),
}));

describe('RegionTags component', () => {
it('renders correctly for different region conditions', () => {
const regions = [
{ id: 1, type: 'box', x: 0.1, y: 0.2, w: 0.3, h: 0.4, highlighted: true, visible: true, editingLabels: false },
{ id: 2, type: 'polygon', x: 0.2, y: 0.3, w: 0.3, h: 0.4, highlighted: true, visible: true, locked: true },
{ id: 3, type: 'line', x: 0.3, y: 0.4, w: 0.3, h: 0.4, highlighted: true, visible: false },
{ id: 4, type: 'keypoints', x: 0.4, y: 0.5, w: 0.3, h: 0.4, highlighted: true, visible: true, minimized: true },
]

const { container } = render(
<RegionTags
regions={regions}
projectRegionBox={mockProjectRegionBox}
mouseEvents={mouseEvents}
regionClsList={regionClsList}
regionTagList={regionTagList}
onBeginRegionEdit={onBeginRegionEdit}
onChangeRegion={onChangeRegion}
onCloseRegionEdit={onCloseRegionEdit}
onDeleteRegion={onDeleteRegion}
layoutParams={layoutParams}
imageSrc={imageSrc}
RegionEditLabel={null}
onRegionClassAdded={onRegionClassAdded}
enabledRegionProps={enabledRegionProps}
/>
)

// Check if the region elements are rendered
expect(container.querySelectorAll('div').length).toBeGreaterThan(0)

// Check if the locked region renders LockIcon
expect(container.querySelector('svg')).toBeInTheDocument()

// Check if the minimized region is not rendered
expect(container.querySelectorAll(`[data-testid="region-4"]`).length).toBe(0)

// Check if the hidden region is not rendered
expect(container.querySelectorAll(`[data-testid="region-3"]`).length).toBe(0)

// // Check if visible and non-minimized regions are rendered
expect(container.querySelectorAll(`[data-testid="region-1"]`).length).toBe(1)
expect(container.querySelectorAll(`[data-testid="region-2"]`).length).toBe(1)
})
})
2 changes: 2 additions & 0 deletions client/src/RegionTags/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ export const RegionTags = ({
return (
<div
key={region.id}
data-testid={`region-${region.id}`}
style={{
position: "absolute",
...coords,
Expand Down Expand Up @@ -82,6 +83,7 @@ export const RegionTags = ({
return (
<div
key={region.id}
data-testid={`region-${region.id}`}
style={{
position: "absolute",
...coords,
Expand Down
71 changes: 71 additions & 0 deletions client/src/SettingsProvider/SettingsProvider.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import SettingsProvider, { SettingsContext } from './index';

// Mock localStorage for testing
let localStorageMock = {};

beforeEach(() => {
localStorageMock = {};

// Mock localStorage.getItem
jest.spyOn(window.localStorage.__proto__, 'getItem').mockImplementation((key) => {
return localStorageMock[key];
});

// Mock localStorage.setItem
jest.spyOn(window.localStorage.__proto__, 'setItem').mockImplementation((key, value) => {
localStorageMock[key] = value.toString();
});

// Mock localStorage.clear
jest.spyOn(window.localStorage.__proto__, 'clear').mockImplementation(() => {
localStorageMock = {};
});
});

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

test('should provide default settings', () => {
const { getByTestId } = render(
<SettingsProvider>
<TestComponent />
</SettingsProvider>
);

expect(getByTestId('showCrosshairs').textContent).toBe('false');
expect(getByTestId('showHighlightBox').textContent).toBe('true');
});

test('should change setting and update state', () => {
const { getByText, getByTestId } = render(
<SettingsProvider>
<TestComponent />
</SettingsProvider>
);

// Simulate changing setting
fireEvent.click(getByText('Toggle Crosshairs'));

// Assert state change in component
expect(getByTestId('showCrosshairs').textContent).toBe('true');
});

// Test component to be rendered inside SettingsProvider for interacting with settings
const TestComponent = () => {
const settings = React.useContext(SettingsContext);

console.log(settings, 'masimis'); // Check what 'settings' actually contains

return (
<div>
<span data-testid="showCrosshairs">{settings && settings.showCrosshairs.toString()}</span>
<span data-testid="showHighlightBox">{settings && settings.showHighlightBox.toString()}</span>
<button onClick={() => settings.changeSetting('showCrosshairs', !settings.showCrosshairs)}>
Toggle Crosshairs
</button>
</div>
);
};
3 changes: 2 additions & 1 deletion client/src/SettingsProvider/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@ const pullSettingsFromLocalStorage = () => {
export const useSettings = () => useContext(SettingsContext)

export const SettingsProvider = ({children}) => {
const [state, changeState] = useState(() => pullSettingsFromLocalStorage())
const localStorageSettings = pullSettingsFromLocalStorage();
const [state, changeState] = useState({ ...defaultSettings, ...localStorageSettings });
const changeSetting = (setting, value) => {
changeState({...state, [setting]: value})
window.localStorage.setItem(`settings_${setting}`, JSON.stringify(value))
Expand Down

0 comments on commit 668a6c9

Please sign in to comment.