Skip to content

Commit

Permalink
test: port tests to ts (#253)
Browse files Browse the repository at this point in the history
  • Loading branch information
toomuchdesign authored Oct 29, 2022
1 parent b098929 commit fcfd66c
Show file tree
Hide file tree
Showing 13 changed files with 148 additions and 51 deletions.
8 changes: 8 additions & 0 deletions @types/@schwingbat/relative-angle/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
declare module '@schwingbat/relative-angle';

type Point = {
x: number;
y: number;
};

export function degrees(objectCoords: Point, targetCoords: Point): number;
12 changes: 12 additions & 0 deletions @types/jest/index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
declare global {
namespace jest {
interface Expect {
toEqualWithRoundingError(expected: number): any;
}
interface Matchers<R = void> {
toEqualWithRoundingError(expected: number): R;
}
}
}

export {};
2 changes: 1 addition & 1 deletion jest.setup.js → jest.setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import '@testing-library/jest-dom/extend-expect';

// https://stackoverflow.com/a/53464807/2902821
expect.extend({
toEqualWithRoundingError(actual, expected, decimals = 12) {
toEqualWithRoundingError(actual: number, expected: number, decimals = 12) {
const pass = Math.abs(expected - actual) < Math.pow(10, -decimals) / 2;
if (pass) {
return {
Expand Down
32 changes: 32 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 5 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,9 @@
"react": "^16.8.0 || ^17.0.0 || ^18",
"react-dom": "^16.8.0 || ^17.0.0 || ^18"
},
"dependencies": {},
"dependencies": {
"@types/svg-path-parser": "^1.1.3"
},
"devDependencies": {
"@babel/core": "^7.12.10",
"@babel/plugin-transform-react-jsx": "^7.12.12",
Expand All @@ -74,6 +76,7 @@
"@testing-library/jest-dom": "^5.11.9",
"@testing-library/react": "^12.0.0",
"@types/react": "^17.0.2",
"@types/react-dom": "^17.0.18",
"all-contributors-cli": "^6.19.0",
"babel-jest": "^27.1.0",
"babel-loader": "^8.2.2",
Expand Down Expand Up @@ -105,7 +108,7 @@
"!**/__tests__/**"
],
"setupFilesAfterEnv": [
"<rootDir>/jest.setup.js"
"<rootDir>/jest.setup.ts"
]
},
"size-limit": [
Expand Down
22 changes: 14 additions & 8 deletions src/__tests__/Chart.test.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// @ts-nocheck
import React from 'react';
import { act, render, dataMock, getArcInfo } from './testUtils';
import { degreesToRadians, extractPercentage } from '../utils';
Expand All @@ -7,7 +6,8 @@ import { pieChartDefaultProps } from '../../src';
jest.useFakeTimers();

beforeAll(() => {
global.requestAnimationFrame = (callback) => {
/// @ts-expect-error: this is a partial mock
global.requestAnimationFrame = (callback: () => void) => {
callback();
return 'id';
};
Expand All @@ -22,6 +22,8 @@ describe('Chart', () => {
children: <defs />,
});
const root = container.firstChild;

// @ts-expect-error: ChildNode type doesn't have tagName prop
expect(root.tagName).toBe('svg');
expect(root).toHaveClass('foo');
expect(root).toHaveStyle({ color: 'green' });
Expand Down Expand Up @@ -118,7 +120,7 @@ describe('Chart', () => {
lengthAngle: 200,
background: 'green',
});
const paths = container.querySelectorAll('path');
const paths = Array.from(container.querySelectorAll('path'));
const [background, segment] = paths;
const backgroundInfo = getArcInfo(background);
const segmentInfo = getArcInfo(segment);
Expand All @@ -145,7 +147,7 @@ describe('Chart', () => {
background: 'green',
rounded: true,
});
const paths = container.querySelectorAll('path');
const paths = Array.from(container.querySelectorAll('path'));
const [background] = paths;
expect(paths.length).toBe(dataMock.length + 1);
expect(background).toHaveAttribute('stroke-linecap', 'round');
Expand Down Expand Up @@ -193,11 +195,11 @@ describe('Chart', () => {
const fullPathLength = degreesToRadians(segmentRadius) * lengthAngle;
let hiddenPercentage;
const initialProps = {
data: [...dataMock[0]],
data: [dataMock[0]],
animate: true,
reveal,
};
const { container, rerender } = render(initialProps);
const { container, reRender } = render(initialProps);
const path = container.querySelector('path');

// Paths are hidden
Expand All @@ -223,7 +225,7 @@ describe('Chart', () => {

// Update reveal prop after initial animation
const newReveal = 77;
rerender({
reRender({
...initialProps,
reveal: newReveal,
});
Expand Down Expand Up @@ -251,14 +253,18 @@ describe('Chart', () => {
jest.runAllTimers();
});

// @ts-expect-error: This is a Jest mocke
console.error.mockRestore();
expect(consoleError).not.toHaveBeenCalled();
});

describe('stroke-dashoffset attribute', () => {
it("doesn't generate zero rounding issues after animation (GitHub: #133)", () => {
const { container } = render({
data: [{ value: 1 }, { value: 1.6 }],
data: [
{ value: 1, color: 'red' },
{ value: 1.6, color: 'blue' },
],
animate: true,
});

Expand Down
29 changes: 14 additions & 15 deletions src/__tests__/Label.test.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
// @ts-nocheck
import React from 'react';
import { render, dataMock, getArcInfo } from './testUtils';
import {
bisectorAngle,
extractPercentage,
shiftVectorAlongAngle,
} from '../utils';
import { pieChartDefaultProps } from '../../src';
import { pieChartDefaultProps, PieChartProps } from '../../src';

function getExpectedLabelRenderProps(dataEntry) {
function getExpectedLabelRenderProps(dataEntry: PieChartProps['data'][number]) {
return {
x: expect.any(Number),
y: expect.any(Number),
Expand Down Expand Up @@ -43,13 +42,13 @@ describe('Label', () => {
describe('returning a value', () => {
const labels = [0, null, 'label'];
describe.each`
description | label | expectedLabels
${'number'} | ${() => -5} | ${[-5, -5, -5]}
${'number'} | ${({ dataIndex }) => dataIndex} | ${[0, 1, 2]}
${'string'} | ${() => 'label'} | ${['label', 'label', 'label']}
${'null'} | ${() => null} | ${[]}
${'undefined'} | ${() => undefined} | ${[]}
${'mixed'} | ${({ dataIndex }) => labels[dataIndex]} | ${[0, 'label']}
description | label | expectedLabels
${'number'} | ${() => -5} | ${[-5, -5, -5]}
${'number'} | ${({ dataIndex }: { dataIndex: number }) => dataIndex} | ${[0, 1, 2]}
${'string'} | ${() => 'label'} | ${['label', 'label', 'label']}
${'null'} | ${() => null} | ${[]}
${'undefined'} | ${() => undefined} | ${[]}
${'mixed'} | ${({ dataIndex }: { dataIndex: number }) => labels[dataIndex]} | ${[0, 'label']}
`('$description', ({ label, expectedLabels }) => {
it('renders expected <text> elements with expected content', () => {
const { container } = render({ label });
Expand All @@ -72,7 +71,7 @@ describe('Label', () => {
});

container.querySelectorAll('text').forEach((label, index) => {
expect(label).toHaveTextContent(index);
expect(label).toHaveTextContent(`${index}`);
});
});
});
Expand All @@ -83,9 +82,9 @@ describe('Label', () => {
const labelPosition = 5;
const expectedDistanceFromCenter = extractPercentage(radius, labelPosition);
describe.each`
description | segmentsShift | expectedSegmentsShift
${'as number'} | ${1} | ${[1, 1, 1]}
${'as function'} | ${(index) => index} | ${[0, 1, 2]}
description | segmentsShift | expectedSegmentsShift
${'as number'} | ${1} | ${[1, 1, 1]}
${'as function'} | ${(index: number) => index} | ${[0, 1, 2]}
`(
'+ segmentShift $description',
({ segmentsShift, expectedSegmentsShift }) => {
Expand Down Expand Up @@ -183,7 +182,7 @@ describe('Label', () => {
'Label $description',
({ labelPosition, startAngle, expectedAlignment }) => {
const { getByText } = render({
data: [{ value: 1 }],
data: [{ value: 1, color: 'red' }],
lineWidth,
lengthAngle,
startAngle,
Expand Down
26 changes: 14 additions & 12 deletions src/__tests__/Path.test.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// @ts-nocheck
import { render, dataMock, getArcInfo, fireEvent } from './testUtils';
import {
bisectorAngle,
Expand All @@ -19,7 +18,10 @@ describe('Path', () => {

it('get empty "d" attributes when data values sum equals 0', () => {
const { container } = render({
data: [{ value: 0 }, { value: 0 }],
data: [
{ value: 0, color: 'red' },
{ value: 0, color: 'green' },
],
});
const paths = container.querySelectorAll('path');
expect(paths.length).toEqual(2);
Expand Down Expand Up @@ -51,11 +53,11 @@ describe('Path', () => {

describe('segmentsStyle prop', () => {
describe.each`
description | segmentsStyle | expectedStyle
${'undefined'} | ${undefined} | ${null}
${'as object'} | ${{ color: 'green' }} | ${{ color: 'green' }}
${'as function'} | ${(i) => ({ color: 'green' })} | ${{ color: 'green' }}
${'as function'} | ${jest.fn((i) => undefined)} | ${null}
description | segmentsStyle | expectedStyle
${'undefined'} | ${undefined} | ${null}
${'as object'} | ${{ color: 'green' }} | ${{ color: 'green' }}
${'as function'} | ${(index: number) => ({ color: 'green' })} | ${{ color: 'green' }}
${'as function'} | ${jest.fn((i) => undefined)} | ${null}
`('$description', ({ segmentsStyle, expectedStyle }) => {
if (jest.isMockFunction(segmentsStyle)) {
it('gets called with expected arguments', () => {
Expand Down Expand Up @@ -86,10 +88,10 @@ describe('Path', () => {
* 3- Compare shifted and non-shifted segments info
*/
describe.each`
description | segmentsShift | expectedSegmentsShift
${'as number'} | ${1} | ${[1, 1, 1]}
${'as function'} | ${(index) => index} | ${[0, 1, 2]}
${'as function'} | ${jest.fn()} | ${[0, 0, 0]}
description | segmentsShift | expectedSegmentsShift
${'as number'} | ${1} | ${[1, 1, 1]}
${'as function'} | ${(index: number) => index} | ${[0, 1, 2]}
${'as function'} | ${jest.fn()} | ${[0, 0, 0]}
`('$description', ({ segmentsShift, expectedSegmentsShift }) => {
if (jest.isMockFunction(segmentsShift)) {
it('gets called with expected arguments', () => {
Expand Down Expand Up @@ -158,7 +160,7 @@ describe('Path', () => {

describe('reveal prop', () => {
const pathLength = degreesToRadians(25) * 360;
const singleEntryDataMock = [...dataMock[0]];
const singleEntryDataMock = [dataMock[0]];

describe('undefined', () => {
it('render a fully revealed path without "strokeDasharray" nor "strokeDashoffset"', () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,20 @@
// https://stackoverflow.com/questions/9017100/calculate-center-of-svg-arc
// https://github.com/Ghostkeeper/SVGToolpathReader/blob/a2bbe90da64e6cd9d54fec553f61ba941001e85d/Parser.py#L493
// @TODO Find a more reliable solution
export function getArcCenter(x1, y1, rx, ry, phi, fA, fS, x2, y2) {
export function getArcCenter(
x1: number,
y1: number,
rx: number,
ry: number,
phi: number,
fA: number,
fS: number,
x2: number,
y2: number
): {
x: number;
y: number;
} {
var cx, cy;

if (rx < 0) {
Expand Down
Loading

0 comments on commit fcfd66c

Please sign in to comment.