level_0
int64 0
10k
| index
int64 0
0
| repo_id
stringlengths 22
152
| file_path
stringlengths 41
203
| content
stringlengths 11
11.5M
|
---|---|---|---|---|
8,181 | 0 | petrpan-code/airbnb/visx/packages/visx-wordcloud | petrpan-code/airbnb/visx/packages/visx-wordcloud/test/Wordcloud.test.tsx | import { render } from '@testing-library/react';
import React from 'react';
import { Wordcloud } from '../src';
import { WordcloudConfig } from '../src/types';
const mocked3Cloud = {
size: jest.fn(),
words: jest.fn(),
random: jest.fn(),
font: jest.fn(),
padding: jest.fn(),
fontSize: jest.fn(),
fontStyle: jest.fn(),
fontWeight: jest.fn(),
rotate: jest.fn(),
spiral: jest.fn(),
on: jest.fn(),
start: jest.fn(),
stop: jest.fn(),
};
jest.mock(
'd3-cloud',
() =>
function d3cloud() {
return mocked3Cloud;
},
);
describe('<Wordcloud />', () => {
afterEach(() => {
for (const mockFn of Object.values(mocked3Cloud)) {
mockFn.mockReset();
}
});
test('it returns early if width or height is zero', () => {
const childrenSpy = jest.fn();
const { rerender } = render(
<Wordcloud width={100} height={0} words={[{ text: 'bla', value: 1 }]}>
{childrenSpy}
</Wordcloud>,
);
expect(childrenSpy).not.toHaveBeenCalled();
rerender(
<Wordcloud width={0} height={200} words={[{ text: 'bla', value: 1 }]}>
{childrenSpy}
</Wordcloud>,
);
expect(childrenSpy).not.toHaveBeenCalled();
});
test('it passes d3 cloud words to the children render function', () => {
const mockWord = { text: 'myMockedWord' };
mocked3Cloud.on.mockImplementation((_, setWords) => setWords([mockWord]));
const childrenSpy = jest.fn();
render(
<Wordcloud width={100} height={100} words={[{ text: 'bla', value: 1 }]}>
{childrenSpy}
</Wordcloud>,
);
expect(childrenSpy).toHaveBeenLastCalledWith([mockWord]);
});
test('it sets the config on the d3 cloud', () => {
const wordcloudConfig: WordcloudConfig<{ text: string }> = {
font: 'Impact',
fontSize: 14,
fontStyle: 'normal',
fontWeight: 'bold',
height: 200,
width: 300,
padding: 4,
random: () => 0.5,
rotate: 0,
spiral: 'archimedean',
words: [{ text: 'myMockedWord' }],
};
render(<Wordcloud {...wordcloudConfig}>{jest.fn()}</Wordcloud>);
expect(mocked3Cloud.size).toHaveBeenCalledWith([wordcloudConfig.width, wordcloudConfig.height]);
expect(mocked3Cloud.font).toHaveBeenCalledWith(wordcloudConfig.font);
expect(mocked3Cloud.fontSize).toHaveBeenCalledWith(wordcloudConfig.fontSize);
expect(mocked3Cloud.fontStyle).toHaveBeenCalledWith(wordcloudConfig.fontStyle);
expect(mocked3Cloud.fontWeight).toHaveBeenCalledWith(wordcloudConfig.fontWeight);
expect(mocked3Cloud.padding).toHaveBeenCalledWith(wordcloudConfig.padding);
expect(mocked3Cloud.random).toHaveBeenCalledWith(wordcloudConfig.random);
expect(mocked3Cloud.rotate).toHaveBeenCalledWith(wordcloudConfig.rotate);
expect(mocked3Cloud.spiral).toHaveBeenCalledWith(wordcloudConfig.spiral);
expect(mocked3Cloud.words).toHaveBeenCalledWith(wordcloudConfig.words);
});
});
|
8,182 | 0 | petrpan-code/airbnb/visx/packages/visx-wordcloud | petrpan-code/airbnb/visx/packages/visx-wordcloud/test/tsconfig.json | {
"compilerOptions": {
"composite": false,
"emitDeclarationOnly": false,
"noEmit": true,
"rootDir": "."
},
"extends": "../../../tsconfig.options.json",
"include": ["**/*", "../types/**/*", "../../../types/**/*"],
"references": [
{
"path": ".."
}
]
}
|
8,183 | 0 | petrpan-code/airbnb/visx/packages/visx-wordcloud | petrpan-code/airbnb/visx/packages/visx-wordcloud/test/useWordcloud.test.ts | import { useWordcloud } from '../src';
describe('useWordcloud', () => {
test('it should be defined', () => {
expect(useWordcloud).toBeDefined();
});
});
|
8,275 | 0 | petrpan-code/airbnb/visx/packages/visx-xychart | petrpan-code/airbnb/visx/packages/visx-xychart/test/theme.test.tsx | import {
lightTheme,
darkTheme,
allColors,
defaultColors,
grayColors,
buildChartTheme,
} from '../src';
describe('colors', () => {
it('should export allColors', () => {
expect(allColors).toMatchObject({ red: expect.arrayContaining([expect.any(String)]) });
expect(Object.keys(allColors)).toHaveLength(13);
});
it('should export defaultColors', () => {
expect(defaultColors).toMatchObject(expect.arrayContaining([expect.any(String)]));
});
it('should export grayColors', () => {
expect(grayColors).toMatchObject(expect.arrayContaining([expect.any(String)]));
});
});
describe('theme', () => {
it('exports a light theme', () => {
expect(lightTheme).toBeDefined();
});
it('exports a dark theme', () => {
expect(darkTheme).toBeDefined();
});
it('builds a theme', () => {
const theme = buildChartTheme({
backgroundColor: 'white',
gridColor: 'fuchsia',
gridColorDark: 'orange',
colors: ['violet'],
gridStyles: { strokeDasharray: '1,5' },
tickLength: 7.5,
svgLabelBig: { fontFamily: 'Comic Sans', fill: 'grape' },
svgLabelSmall: { fontSize: 100, fill: 'banana' },
xTickLineStyles: { strokeWidth: 2.4 },
});
expect(theme).toMatchObject({
backgroundColor: 'white',
colors: ['violet'],
gridStyles: { stroke: 'fuchsia', strokeDasharray: '1,5' },
htmlLabel: { color: 'grape' },
svgLabelBig: { fill: 'grape' },
svgLabelSmall: { fill: 'banana' },
axisStyles: {
x: {
top: {
axisLabel: { fontFamily: 'Comic Sans', fill: 'grape' },
axisLine: { stroke: 'orange' },
tickLabel: { fill: 'banana', fontSize: 100 },
tickLine: { strokeWidth: 2.4 },
},
},
y: {
left: {
axisLabel: { fontFamily: 'Comic Sans', fill: 'grape' },
axisLine: { stroke: 'fuchsia' },
tickLabel: { fill: 'banana', fontSize: 100 },
tickLine: { strokeWidth: 1 },
},
},
},
});
});
});
|
8,276 | 0 | petrpan-code/airbnb/visx/packages/visx-xychart | petrpan-code/airbnb/visx/packages/visx-xychart/test/tsconfig.json | {
"compilerOptions": {
"composite": false,
"emitDeclarationOnly": false,
"noEmit": true,
"rootDir": "."
},
"extends": "../../../tsconfig.options.json",
"include": ["**/*", "../types/**/*", "../../../types/**/*"],
"references": [
{
"path": ".."
}
]
}
|
8,278 | 0 | petrpan-code/airbnb/visx/packages/visx-xychart/test | petrpan-code/airbnb/visx/packages/visx-xychart/test/classes/DataRegistry.test.ts | import DataRegistry from '../../src/classes/DataRegistry';
const data = { key: 'visx', data: [], xAccessor: () => 'x', yAccessor: () => 'y' };
describe('DataRegistry', () => {
it('should be defined', () => {
expect(DataRegistry).toBeDefined();
});
it('should register one data', () => {
const reg = new DataRegistry();
reg.registerData(data);
expect(reg.get('visx')).toBe(data);
expect(reg.keys()).toEqual(['visx']);
});
it('should register multiple data', () => {
const data2 = { key: 'd3', data: [], xAccessor: () => 'x2', yAccessor: () => 'y2' };
const reg = new DataRegistry();
reg.registerData([data, data2]);
expect(reg.get('visx')).toBe(data);
expect(reg.get('d3')).toBe(data2);
expect(reg.keys()).toEqual(['visx', 'd3']);
});
it('should de-register data', () => {
const reg = new DataRegistry();
reg.registerData(data);
expect(reg.get('visx')).toBe(data);
reg.unregisterData('visx');
expect(reg.get('visx')).toBeUndefined();
});
});
|
8,279 | 0 | petrpan-code/airbnb/visx/packages/visx-xychart/test | petrpan-code/airbnb/visx/packages/visx-xychart/test/components/Annotation.test.tsx | import React from 'react';
import { render } from '@testing-library/react';
import '@testing-library/jest-dom';
import { DataContext, Annotation, AnimatedAnnotation } from '../../src';
import getDataContext from '../mocks/getDataContext';
const series = { key: 'visx', data: [{}], xAccessor: () => 4, yAccessor: () => 7 };
function setup(children: React.ReactNode) {
return render(
<DataContext.Provider value={getDataContext(series)}>
<svg>{children}</svg>
</DataContext.Provider>,
);
}
describe('<Annotation />', () => {
it('should be defined', () => {
expect(Annotation).toBeDefined();
});
it('should render a VxAnnotation', () => {
const { getByText } = setup(
<Annotation dataKey={series.key} datum={{}}>
{'test'}
</Annotation>,
);
expect(getByText('test')).toBeInTheDocument();
});
it('should render a VxEditableAnnotation when editable=true', () => {
const { container } = setup(
<Annotation editable dataKey={series.key} datum={{}}>
{'test'}
</Annotation>,
);
// with editable=true, the svg should have a circle overlay with 'cursor: grab' attribute
const CircleElement = container.querySelector('circle');
expect(CircleElement).toHaveAttribute('cursor');
});
});
describe('<AnimatedAnnotation />', () => {
it('should be defined', () => {
expect(AnimatedAnnotation).toBeDefined();
});
it('should render a VxAnnotation', () => {
const { getByText } = setup(
<AnimatedAnnotation dataKey={series.key} datum={{}}>
{'test'}
</AnimatedAnnotation>,
);
expect(getByText('test')).toBeInTheDocument();
});
it('should render a VxEditableAnnotation when editable=true', () => {
const { container } = setup(
<AnimatedAnnotation editable dataKey={series.key} datum={{}}>
{'test'}
</AnimatedAnnotation>,
);
// with editable=true, the svg should have a circle overlay with 'cursor: grab' attribute
const CircleElement = container.querySelector('circle');
expect(CircleElement).toHaveAttribute('cursor');
});
});
|
8,280 | 0 | petrpan-code/airbnb/visx/packages/visx-xychart/test | petrpan-code/airbnb/visx/packages/visx-xychart/test/components/AnnotationCircleSubject.test.tsx | import React from 'react';
import { shallow } from 'enzyme';
import { CircleSubject as VxAnnotationCircleSubject } from '@visx/annotation';
import { AnnotationCircleSubject } from '../../src';
describe('<AnnotationCircleSubject />', () => {
it('should be defined', () => {
expect(AnnotationCircleSubject).toBeDefined();
});
it('should render a VxAnnotationCircleSubject', () => {
const wrapper = shallow(<AnnotationCircleSubject />);
expect(wrapper.find(VxAnnotationCircleSubject)).toHaveLength(1);
});
});
|
8,281 | 0 | petrpan-code/airbnb/visx/packages/visx-xychart/test | petrpan-code/airbnb/visx/packages/visx-xychart/test/components/AnnotationConnector.test.tsx | import React from 'react';
import { shallow } from 'enzyme';
import { Connector as VxAnnotationConnector } from '@visx/annotation';
import { AnnotationConnector } from '../../src';
describe('<AnnotationConnector />', () => {
it('should be defined', () => {
expect(AnnotationConnector).toBeDefined();
});
it('should render a VxAnnotationConnector', () => {
const wrapper = shallow(<AnnotationConnector />);
expect(wrapper.find(VxAnnotationConnector)).toHaveLength(1);
});
});
|
8,282 | 0 | petrpan-code/airbnb/visx/packages/visx-xychart/test | petrpan-code/airbnb/visx/packages/visx-xychart/test/components/AnnotationLabel.test.tsx | import React from 'react';
import { shallow } from 'enzyme';
import { Label as VxAnnotationLabel } from '@visx/annotation';
import { AnnotationLabel } from '../../src';
describe('<AnnotationLabel />', () => {
it('should be defined', () => {
expect(AnnotationLabel).toBeDefined();
});
it('should render a VxAnnotationLabel', () => {
const wrapper = shallow(<AnnotationLabel />);
expect(wrapper.find(VxAnnotationLabel)).toHaveLength(1);
});
});
|
8,283 | 0 | petrpan-code/airbnb/visx/packages/visx-xychart/test | petrpan-code/airbnb/visx/packages/visx-xychart/test/components/AnnotationLineSubject.test.tsx | import React from 'react';
import { shallow } from 'enzyme';
import { LineSubject as VxAnnotationLineSubject } from '@visx/annotation';
import { AnnotationLineSubject } from '../../src';
describe('<AnnotationLineSubject />', () => {
it('should be defined', () => {
expect(AnnotationLineSubject).toBeDefined();
});
it('should render a VxAnnotationLineSubject', () => {
const wrapper = shallow(<AnnotationLineSubject />);
expect(wrapper.find(VxAnnotationLineSubject)).toHaveLength(1);
});
});
|
8,284 | 0 | petrpan-code/airbnb/visx/packages/visx-xychart/test | petrpan-code/airbnb/visx/packages/visx-xychart/test/components/AreaSeries.test.tsx | import React, { useContext, useEffect } from 'react';
import { render } from '@testing-library/react';
import '@testing-library/jest-dom';
import { AnimatedAreaSeries, DataContext, AreaSeries, useEventEmitter } from '../../src';
import getDataContext from '../mocks/getDataContext';
import setupTooltipTest from '../mocks/setupTooltipTest';
import { XYCHART_EVENT_SOURCE } from '../../src/constants';
const series = { key: 'line', data: [{}], xAccessor: () => 4, yAccessor: () => 7 };
describe('<AreaSeries />', () => {
it('should be defined', () => {
expect(AreaSeries).toBeDefined();
});
it('should render an Area', () => {
const { container } = render(
<DataContext.Provider value={getDataContext(series)}>
<svg>
<AreaSeries dataKey={series.key} {...series} />
</svg>
</DataContext.Provider>,
);
const Path = container.querySelector('path');
expect(Path).toBeInTheDocument();
});
it('should set strokeLinecap="round" to make datum surrounded by nulls visible', () => {
const { container } = render(
<DataContext.Provider value={getDataContext(series)}>
<svg>
<AreaSeries dataKey={series.key} renderLine={false} {...series} />
</svg>
</DataContext.Provider>,
);
const Path = container.querySelector('path');
expect(Path).toBeInTheDocument();
expect(Path).toHaveAttribute('stroke-linecap', 'round');
});
it('should use x/y0Accessors in an Area', () => {
const y0Accessor = jest.fn(() => 3);
const { container } = render(
<DataContext.Provider value={getDataContext(series)}>
<svg>
<AreaSeries dataKey={series.key} {...series} y0Accessor={y0Accessor} />
</svg>
</DataContext.Provider>,
);
const Path = container.querySelector('path');
expect(Path).toBeInTheDocument();
expect(y0Accessor).toHaveBeenCalled();
});
it('should render a LinePath is renderLine=true', () => {
const { container } = render(
<DataContext.Provider value={getDataContext(series)}>
<svg>
<AreaSeries renderLine dataKey={series.key} {...series} />
</svg>
</DataContext.Provider>,
);
const LinePath = container.querySelector('.visx-line');
expect(LinePath).toBeInTheDocument();
});
it('should render Glyphs if focus/blur handlers are set', () => {
const { container } = render(
<DataContext.Provider value={getDataContext(series)}>
<svg>
<AreaSeries dataKey={series.key} {...series} onFocus={() => {}} />
</svg>
</DataContext.Provider>,
);
const Circles = container.querySelectorAll('circle');
expect(Circles).toHaveLength(series.data.length);
});
it('should invoke showTooltip/hideTooltip on pointermove/pointerout', () => {
expect.assertions(2);
const showTooltip = jest.fn();
const hideTooltip = jest.fn();
const EventEmitter = () => {
const emit = useEventEmitter();
useEffect(() => {
if (emit) {
emit('pointermove', new MouseEvent('pointermove'), XYCHART_EVENT_SOURCE);
expect(showTooltip).toHaveBeenCalledTimes(1);
emit('pointerout', new MouseEvent('pointerout'), XYCHART_EVENT_SOURCE);
expect(showTooltip).toHaveBeenCalledTimes(1);
}
});
return null;
};
const ConditionalEventEmitter = () => {
const { dataRegistry } = useContext(DataContext);
// AreaSeries won't render until its data is registered
// wait for that to emit the events
return dataRegistry?.get(series.key) ? <EventEmitter /> : null;
};
setupTooltipTest(
<>
<AreaSeries dataKey={series.key} {...series} />
<ConditionalEventEmitter />
</>,
{ showTooltip, hideTooltip },
);
});
});
describe('<AnimatedAreaSeries />', () => {
it('should be defined', () => {
expect(AnimatedAreaSeries).toBeDefined();
});
it('should render an animated.path', () => {
const { container } = render(
<DataContext.Provider value={getDataContext(series)}>
<svg>
<AnimatedAreaSeries renderLine={false} dataKey={series.key} {...series} />
</svg>
</DataContext.Provider>,
);
const Path = container.querySelectorAll('path');
expect(Path).toHaveLength(1);
});
});
|
8,285 | 0 | petrpan-code/airbnb/visx/packages/visx-xychart/test | petrpan-code/airbnb/visx/packages/visx-xychart/test/components/AreaStack.test.tsx | import React, { useContext, useEffect } from 'react';
import { render } from '@testing-library/react';
import '@testing-library/jest-dom';
import {
AreaStack,
AreaSeries,
DataProvider,
DataContext,
useEventEmitter,
AnimatedAreaStack,
} from '../../src';
import setupTooltipTest from '../mocks/setupTooltipTest';
import { XYCHART_EVENT_SOURCE } from '../../src/constants';
const providerProps = {
initialDimensions: { width: 100, height: 100 },
xScale: { type: 'linear' },
yScale: { type: 'linear' },
} as const;
const accessors = {
xAccessor: (d: { x?: number }) => d.x,
yAccessor: (d: { y?: number }) => d.y,
};
const series1 = {
key: 'area1',
data: [
{ x: 10, y: 5 },
{ x: 7, y: 5 },
],
...accessors,
};
const series2 = {
key: 'area2',
data: [
{ x: 10, y: 5 },
{ x: 7, y: 20 },
],
...accessors,
};
describe('<AreaStack />', () => {
it('should be defined', () => {
expect(AreaSeries).toBeDefined();
});
it('should render Areas', () => {
const { container } = render(
<DataProvider {...providerProps}>
<svg>
<AreaStack>
<AreaSeries dataKey={series1.key} {...series1} />
<AreaSeries dataKey={series2.key} {...series2} />
</AreaStack>
</svg>
</DataProvider>,
);
const Areas = container.querySelectorAll('.visx-area');
expect(Areas).toHaveLength(2);
});
it('should render LinePaths if renderLine=true', () => {
const { container } = render(
<DataProvider {...providerProps}>
<svg>
<AreaStack renderLine>
<AreaSeries dataKey={series1.key} {...series1} />
<AreaSeries dataKey={series2.key} {...series2} />
</AreaStack>
</svg>
</DataProvider>,
);
const LinePaths = container.querySelectorAll('.visx-line');
expect(LinePaths).toHaveLength(2);
});
it('should render Glyphs if focus/blur handlers are set', () => {
const { container } = render(
<DataProvider {...providerProps}>
<svg>
<AreaStack onFocus={() => {}}>
<AreaSeries dataKey={series1.key} {...series1} />
</AreaStack>
</svg>
</DataProvider>,
);
const Circles = container.querySelectorAll('circle');
expect(Circles).toHaveLength(series1.data.length);
});
it('should update scale domain to include stack sums including negative values', () => {
expect.hasAssertions();
function Assertion() {
const { yScale } = useContext(DataContext);
// eslint-disable-next-line jest/no-if
if (yScale) {
expect(yScale.domain()).toEqual([-20, 10]);
}
return null;
}
render(
<DataProvider {...providerProps}>
<svg>
<AreaStack>
<AreaSeries dataKey={series1.key} {...series1} />
<AreaSeries
dataKey={series2.key}
{...series2}
data={[
{ x: 10, y: 5 },
{ x: 7, y: -20 },
]}
/>
</AreaStack>
</svg>
<Assertion />
</DataProvider>,
);
});
it('should invoke showTooltip/hideTooltip on pointermove/pointerout', () => {
expect.assertions(2);
const showTooltip = jest.fn();
const hideTooltip = jest.fn();
const EventEmitter = () => {
const emit = useEventEmitter();
const { yScale } = useContext(DataContext);
useEffect(() => {
// checking for yScale ensures stack data is registered and stacks are rendered
if (emit && yScale) {
// @ts-expect-error not a React.MouseEvent
emit('pointermove', new MouseEvent('pointermove'), XYCHART_EVENT_SOURCE);
expect(showTooltip).toHaveBeenCalledTimes(2); // one per key
// @ts-expect-error not a React.MouseEvent
emit('pointerout', new MouseEvent('pointerout'), XYCHART_EVENT_SOURCE);
expect(showTooltip).toHaveBeenCalled();
}
});
return null;
};
setupTooltipTest(
<>
<AreaStack>
<AreaSeries dataKey={series1.key} {...series1} />
<AreaSeries dataKey={series2.key} {...series2} />
</AreaStack>
<EventEmitter />
</>,
{ showTooltip, hideTooltip },
);
});
});
describe('<AnimatedAreaStack />', () => {
it('should be defined', () => {
expect(AnimatedAreaStack).toBeDefined();
});
it('should render an animated.path', () => {
const { container } = render(
<DataProvider {...providerProps}>
<svg>
<AnimatedAreaStack renderLine={false}>
<AreaSeries dataKey={series1.key} {...series1} />
<AreaSeries dataKey={series2.key} {...series2} />
</AnimatedAreaStack>
</svg>
</DataProvider>,
);
const Circles = container.querySelectorAll('path');
expect(Circles).toHaveLength(2);
});
});
|
8,286 | 0 | petrpan-code/airbnb/visx/packages/visx-xychart/test | petrpan-code/airbnb/visx/packages/visx-xychart/test/components/Axis.test.tsx | import React from 'react';
import { render } from '@testing-library/react';
import '@testing-library/jest-dom';
import { scaleLinear } from '@visx/scale';
import BaseAxis from '../../src/components/axis/BaseAxis';
import { Axis, AnimatedAxis, DataContext, lightTheme } from '../../src';
import getDataContext from '../mocks/getDataContext';
const series = { key: 'visx', data: [{}], xAccessor: () => 4, yAccessor: () => 7 };
function setup(
children: React.ReactNode,
contextOverrides?: Partial<ReturnType<typeof getDataContext>>,
) {
return render(
<DataContext.Provider value={{ ...getDataContext(series), ...contextOverrides }}>
<svg>{children}</svg>
</DataContext.Provider>,
);
}
describe('<Axis />', () => {
it('should be defined', () => {
expect(Axis).toBeDefined();
});
it('should render a VxAxis', () => {
expect(
setup(<Axis orientation="bottom" />).container.querySelectorAll('.visx-axis'),
).toHaveLength(1);
});
});
describe('<AnimatedAxis />', () => {
it('should be defined', () => {
expect(AnimatedAxis).toBeDefined();
});
it('should render a VxAnimatedAxis', () => {
expect(
setup(<AnimatedAxis orientation="bottom" />).container.querySelectorAll('.visx-axis'),
).toHaveLength(1);
});
});
describe('<BaseAxis />', () => {
it('should be defined', () => {
expect(BaseAxis).toBeDefined();
});
it('<BaseAxis/> renders', () => {
const { container } = setup(
<BaseAxis orientation="top" AxisComponent={() => <Axis orientation="top" />} />,
);
const AxisComponents = container.querySelectorAll('.visx-axis');
expect(AxisComponents).toHaveLength(1);
});
it('should use scale=xScale for orientation=top (or bottom)', () => {
const xScale = scaleLinear({ domain: [0, 4], range: [0, 10] });
const { container } = setup(
<BaseAxis orientation="top" AxisComponent={() => <Axis orientation="top" />} />,
{ xScale },
);
const TickLabels = container.querySelectorAll('tspan');
expect(TickLabels[0].textContent).toBe('0.0');
expect(TickLabels[0]).toHaveAttribute('x', '0');
expect(TickLabels[TickLabels.length - 1].textContent).toBe('4.0');
expect(TickLabels[TickLabels.length - 1]).toHaveAttribute('x', '10');
});
it('should use scale=yScale for orientation=left (or right)', () => {
const yScale = scaleLinear({ domain: [0, 4], range: [0, 10] });
const { container } = setup(
<BaseAxis orientation="left" AxisComponent={() => <Axis orientation="left" />} />,
{ yScale },
);
const TickLabels = container.querySelectorAll('tspan');
expect(TickLabels[0].textContent).toBe('0.0');
expect(TickLabels[0].parentNode).toHaveAttribute('y', '0');
expect(TickLabels[TickLabels.length - 1].textContent).toBe('4.0');
expect(TickLabels[TickLabels.length - 1].parentNode).toHaveAttribute('y', '10');
});
it('should use axis styles from context theme unless specified in props', () => {
const axisStyles = lightTheme.axisStyles.x.top;
const { container } = setup(
<BaseAxis
orientation="left"
AxisComponent={() => <Axis orientation="top" stroke="#22222" tickLength={12345} />}
/>,
);
const VisxAxisLine = container.querySelector('.visx-axis-line');
const VisxLine = container.querySelector('.visx-line');
// specified styles in the props
expect(VisxAxisLine).toHaveAttribute('stroke', '#22222');
// tick length = y1-y2 of axis line
expect(VisxLine).toHaveAttribute('y1', '0');
expect(VisxLine).toHaveAttribute('y2', '-12345');
// context theme styles
expect(VisxLine).toHaveAttribute('stroke-width', `${axisStyles.axisLine.strokeWidth}`);
expect(VisxLine).toHaveAttribute('stroke', axisStyles.tickLine.stroke);
});
it('should accept props for tickline', () => {
const tickLineProps = { strokeWidth: 12345, stroke: 'banana', opacity: 0.5 };
const { container } = setup(
<BaseAxis
orientation="left"
AxisComponent={() => <AnimatedAxis orientation="top" tickLineProps={tickLineProps} />}
/>,
);
const VisxAxisTick = container.querySelector('.visx-axis-tick > line');
// specified styles in the props
expect(VisxAxisTick).toHaveAttribute('stroke-width', `${tickLineProps.strokeWidth}`);
expect(VisxAxisTick).toHaveAttribute('stroke', `${tickLineProps.stroke}`);
expect(VisxAxisTick).toHaveAttribute('opacity', `${tickLineProps.opacity}`);
});
});
|
8,287 | 0 | petrpan-code/airbnb/visx/packages/visx-xychart/test | petrpan-code/airbnb/visx/packages/visx-xychart/test/components/BarGroup.test.tsx | import React, { useContext, useEffect } from 'react';
import '@testing-library/jest-dom';
import { render } from '@testing-library/react';
import {
AnimatedBarGroup,
BarGroup,
BarSeries,
DataContext,
DataProvider,
useEventEmitter,
} from '../../src';
import setupTooltipTest from '../mocks/setupTooltipTest';
import { XYCHART_EVENT_SOURCE } from '../../src/constants';
const providerProps = {
initialDimensions: { width: 100, height: 100 },
xScale: { type: 'linear' },
yScale: { type: 'linear' },
} as const;
const accessors = {
xAccessor: (d: { x?: number }) => d.x,
yAccessor: (d: { y?: number }) => d.y,
};
const series1 = {
key: 'bar1',
data: [
{ x: 10, y: 5 },
{ x: 7, y: 5 },
],
...accessors,
};
const series2 = {
key: 'bar2',
data: [
{ x: 10, y: 5 },
{ x: 7, y: 20 },
],
...accessors,
};
const seriesMissingData = {
key: 'seriesMissingData',
data: [{ y: 5 }, { x: 7 }, { x: 7, y: 20 }],
...accessors,
};
describe('<BarGroup />', () => {
it('should be defined', () => {
expect(BarSeries).toBeDefined();
});
it('should render rects', () => {
const { container } = render(
<DataProvider {...providerProps}>
<svg>
<BarGroup>
<BarSeries dataKey={series1.key} {...series1} />
<BarSeries dataKey={series2.key} {...series2} />
</BarGroup>
</svg>
</DataProvider>,
);
expect(container.querySelectorAll('rect')).toHaveLength(4);
});
it('should render BarRounded if radius is set', () => {
const { container } = render(
<DataProvider {...providerProps}>
<svg>
<BarGroup>
<BarSeries dataKey={series1.key} radiusAll radius={4} {...series1} />
<BarSeries dataKey={series2.key} {...series2} />
</BarGroup>
</svg>
</DataProvider>,
);
expect(container.querySelectorAll('path')).toHaveLength(2);
});
it('should use colorAccessor if passed', () => {
const { container } = render(
<DataProvider {...providerProps}>
<svg>
<BarGroup>
<BarSeries dataKey={series1.key} {...series1} />
<BarSeries
dataKey={series2.key}
{...series2}
colorAccessor={(_, i) => (i === 0 ? 'banana' : null)}
/>
</BarGroup>
</svg>
</DataProvider>,
);
const rects = container.querySelectorAll('rect');
expect(rects[0]).not.toHaveAttribute('fill', 'banana');
expect(rects[1]).not.toHaveAttribute('fill', 'banana');
expect(rects[2]).toHaveAttribute('fill', 'banana');
expect(rects[3]).not.toHaveAttribute('fill', 'banana');
});
it('should not render rects with invalid x or y', () => {
const { container } = render(
<DataProvider {...providerProps}>
<svg>
<BarGroup>
<BarSeries dataKey={series1.key} {...series1} />
<BarSeries dataKey={seriesMissingData.key} {...seriesMissingData} />
</BarGroup>
</svg>
</DataProvider>,
);
expect(container.querySelectorAll('rect')).toHaveLength(3);
});
it('should invoke showTooltip/hideTooltip on pointermove/pointerout', () => {
expect.assertions(2);
const showTooltip = jest.fn();
const hideTooltip = jest.fn();
const EventEmitter = () => {
const emit = useEventEmitter();
const { yScale } = useContext(DataContext);
useEffect(() => {
// checking for yScale ensures stack data is registered and stacks are rendered
if (emit && yScale) {
// @ts-expect-error not a React.MouseEvent
emit('pointermove', new MouseEvent('pointermove'), XYCHART_EVENT_SOURCE);
expect(showTooltip).toHaveBeenCalledTimes(2); // one per key
// @ts-expect-error not a React.MouseEvent
emit('pointerout', new MouseEvent('pointerout'), XYCHART_EVENT_SOURCE);
expect(showTooltip).toHaveBeenCalled();
}
});
return null;
};
setupTooltipTest(
<>
<BarGroup>
<BarSeries dataKey={series1.key} {...series1} />
<BarSeries dataKey={series2.key} {...series2} />
</BarGroup>
<EventEmitter />
</>,
{ showTooltip, hideTooltip },
);
});
});
describe('<AnimatedBarGroup />', () => {
it('should be defined', () => {
expect(AnimatedBarGroup).toBeDefined();
});
it('should render an animated.rect', () => {
const { container } = render(
<DataProvider {...providerProps}>
<svg>
<AnimatedBarGroup>
<BarSeries dataKey={series1.key} {...series1} />
<BarSeries dataKey={series2.key} {...series2} />
</AnimatedBarGroup>
</svg>
</DataProvider>,
);
expect(container.querySelectorAll('rect')).toHaveLength(4);
});
});
|
8,288 | 0 | petrpan-code/airbnb/visx/packages/visx-xychart/test | petrpan-code/airbnb/visx/packages/visx-xychart/test/components/BarSeries.test.tsx | import React, { useContext, useEffect } from 'react';
import { render } from '@testing-library/react';
import '@testing-library/jest-dom';
import { DataContext, AnimatedBarSeries, BarSeries, useEventEmitter } from '../../src';
import getDataContext from '../mocks/getDataContext';
import setupTooltipTest from '../mocks/setupTooltipTest';
import { XYCHART_EVENT_SOURCE } from '../../src/constants';
const series = { key: 'bar', data: [{}, {}], xAccessor: () => 0, yAccessor: () => 10 };
const seriesMissingData = {
key: 'barMissingData',
data: [{ x: 1 }, { x: 0, y: 3 }, { y: 2 }],
xAccessor: (d: { x?: number }) => d.x,
yAccessor: (d: { y?: number }) => d.y,
};
describe('<BarSeries />', () => {
it('should be defined', () => {
expect(BarSeries).toBeDefined();
});
it('should render rects', () => {
const { container } = render(
<DataContext.Provider value={getDataContext(series)}>
<svg>
<BarSeries dataKey={series.key} {...series} />
</svg>
</DataContext.Provider>,
);
expect(container.querySelectorAll('rect')).toHaveLength(2);
});
it('should render rounded rects if radius is set', () => {
const { container } = render(
<DataContext.Provider value={getDataContext(series)}>
<svg>
<BarSeries dataKey={series.key} radiusAll radius={4} {...series} />
</svg>
</DataContext.Provider>,
);
expect(container.querySelectorAll('path')).toHaveLength(2);
});
it('should use colorAccessor if passed', () => {
const { container } = render(
<DataContext.Provider value={getDataContext(series)}>
<svg>
<BarSeries
dataKey={series.key}
{...series}
colorAccessor={(_, i) => (i === 0 ? 'banana' : null)}
/>
</svg>
</DataContext.Provider>,
);
const rects = container.querySelectorAll('rect');
expect(rects[0]).toHaveAttribute('fill', 'banana');
expect(rects[1]).not.toHaveAttribute('fill', 'banana');
});
it('should not render rects if x or y is invalid', () => {
const { container } = render(
<DataContext.Provider value={getDataContext(seriesMissingData)}>
<svg>
<BarSeries dataKey={seriesMissingData.key} {...seriesMissingData} />
</svg>
</DataContext.Provider>,
);
expect(container.querySelectorAll('rect')).toHaveLength(1);
});
it('should invoke showTooltip/hideTooltip on pointermove/pointerout', () => {
expect.assertions(2);
const showTooltip = jest.fn();
const hideTooltip = jest.fn();
const EventEmitter = () => {
const emit = useEventEmitter();
useEffect(() => {
if (emit) {
emit('pointermove', new MouseEvent('pointermove'), XYCHART_EVENT_SOURCE);
expect(showTooltip).toHaveBeenCalledTimes(1);
emit('pointerout', new MouseEvent('pointerout'), XYCHART_EVENT_SOURCE);
expect(showTooltip).toHaveBeenCalledTimes(1);
}
});
return null;
};
const ConditionalEventEmitter = () => {
const { dataRegistry } = useContext(DataContext);
// BarSeries won't render until its data is registered
// wait for that to emit the events
return dataRegistry?.get(series.key) ? <EventEmitter /> : null;
};
setupTooltipTest(
<>
<BarSeries dataKey={series.key} {...series} />
<ConditionalEventEmitter />
</>,
{ showTooltip, hideTooltip },
);
});
});
describe('<AnimatedBarSeries />', () => {
it('should be defined', () => {
expect(AnimatedBarSeries).toBeDefined();
});
it('should render an animated.rect', () => {
const { container } = render(
<DataContext.Provider value={getDataContext(series)}>
<svg>
<AnimatedBarSeries dataKey={series.key} {...series} />
</svg>
</DataContext.Provider>,
);
expect(container.querySelectorAll('rect')).toHaveLength(series.data.length);
});
});
|
8,289 | 0 | petrpan-code/airbnb/visx/packages/visx-xychart/test | petrpan-code/airbnb/visx/packages/visx-xychart/test/components/BarStack.test.tsx | import React, { useContext, useEffect } from 'react';
import { render } from '@testing-library/react';
import '@testing-library/jest-dom';
import {
BarStack,
BarSeries,
DataProvider,
DataContext,
useEventEmitter,
AnimatedBarStack,
} from '../../src';
import setupTooltipTest from '../mocks/setupTooltipTest';
import { XYCHART_EVENT_SOURCE } from '../../src/constants';
const providerProps = {
initialDimensions: { width: 100, height: 100 },
xScale: { type: 'linear' },
yScale: { type: 'linear' },
} as const;
const accessors = {
xAccessor: (d: { x?: number }) => d.x,
yAccessor: (d: { y?: number }) => d.y,
};
const series1 = {
key: 'bar1',
data: [
{ x: 10, y: 5 },
{ x: 7, y: 5 },
],
...accessors,
};
const series2 = {
key: 'bar2',
data: [
{ x: 10, y: 5 },
{ x: 7, y: 20 },
],
...accessors,
};
const seriesMissingData = {
key: 'seriesMissingData',
data: [{ y: 5 }, { x: 7 }, { x: 7, y: 20 }],
...accessors,
};
describe('<BarStack />', () => {
it('should be defined', () => {
expect(BarSeries).toBeDefined();
});
it('should render rects', () => {
const { container } = render(
<DataProvider {...providerProps}>
<svg>
<BarStack>
<BarSeries dataKey={series1.key} {...series1} />
<BarSeries dataKey={series2.key} {...series2} />
</BarStack>
</svg>
</DataProvider>,
);
const RectElements = container.querySelectorAll('rect');
expect(RectElements).toHaveLength(4);
});
it('should render BarRounded if radius is set', () => {
const { container } = render(
<DataProvider {...providerProps}>
<svg>
<BarStack>
<BarSeries dataKey={series1.key} radiusAll radius={4} {...series1} />
<BarSeries dataKey={series2.key} {...series2} />
</BarStack>
</svg>
</DataProvider>,
);
expect(container.querySelectorAll('path')).toHaveLength(2);
});
it('should use colorAccessor if passed', () => {
const { container } = render(
<DataProvider {...providerProps}>
<svg>
<BarStack>
<BarSeries dataKey={series1.key} {...series1} />
<BarSeries
dataKey={series2.key}
{...series2}
colorAccessor={(_, i) => (i === 0 ? 'banana' : null)}
/>
</BarStack>
</svg>
</DataProvider>,
);
const RectElements = container.querySelectorAll('rect');
expect(RectElements[0]).not.toHaveAttribute('fill', 'banana');
expect(RectElements[1]).not.toHaveAttribute('fill', 'banana');
expect(RectElements[2]).toHaveAttribute('fill', 'banana');
expect(RectElements[3]).not.toHaveAttribute('fill', 'banana');
});
it('should not render rects if x or y are invalid', () => {
const { container } = render(
<DataProvider {...providerProps}>
<svg>
<BarStack>
<BarSeries dataKey={series1.key} {...series1} />
<BarSeries dataKey={seriesMissingData.key} {...seriesMissingData} />
</BarStack>
</svg>
</DataProvider>,
);
const RectElements = container.querySelectorAll('rect');
expect(RectElements).toHaveLength(3);
});
it('should update scale domain to include stack sums including negative values', () => {
expect.hasAssertions();
function Assertion() {
const { yScale, dataRegistry } = useContext(DataContext);
// eslint-disable-next-line jest/no-if
if (yScale && dataRegistry?.keys().length === 2) {
expect(yScale.domain()).toEqual([-20, 10]);
}
return null;
}
render(
<DataProvider {...providerProps}>
<svg>
<BarStack>
<BarSeries dataKey={series1.key} {...series1} />
<BarSeries
dataKey={series2.key}
{...series2}
data={[
{ x: 10, y: 5 },
{ x: 7, y: -20 },
]}
/>
</BarStack>
</svg>
<Assertion />
</DataProvider>,
);
});
it('should invoke showTooltip/hideTooltip on pointermove/pointerout', () => {
expect.assertions(2);
const showTooltip = jest.fn();
const hideTooltip = jest.fn();
const EventEmitter = () => {
const emit = useEventEmitter();
const { yScale } = useContext(DataContext);
useEffect(() => {
// checking for yScale ensures stack data is registered and stacks are rendered
if (emit && yScale) {
// not a React.MouseEvent
emit('pointermove', new MouseEvent('pointermove'), XYCHART_EVENT_SOURCE);
expect(showTooltip).toHaveBeenCalledTimes(2); // one per key
// not a React.MouseEvent
emit('pointerout', new MouseEvent('pointerout'), XYCHART_EVENT_SOURCE);
expect(showTooltip).toHaveBeenCalled();
}
});
return null;
};
setupTooltipTest(
<>
<BarStack>
<BarSeries dataKey={series1.key} {...series1} />
<BarSeries dataKey={series2.key} {...series2} />
</BarStack>
<EventEmitter />
</>,
{ showTooltip, hideTooltip },
);
});
});
describe('<AnimatedBarStack />', () => {
it('should be defined', () => {
expect(AnimatedBarStack).toBeDefined();
});
it('should render an animated.rect', () => {
const { container } = render(
<DataProvider {...providerProps}>
<svg>
<AnimatedBarStack>
<BarSeries dataKey={series1.key} {...series1} />
<BarSeries dataKey={series2.key} {...series2} />
</AnimatedBarStack>
</svg>
</DataProvider>,
);
const RectElements = container.querySelectorAll('rect');
expect(RectElements).toHaveLength(4);
});
});
|
8,290 | 0 | petrpan-code/airbnb/visx/packages/visx-xychart/test | petrpan-code/airbnb/visx/packages/visx-xychart/test/components/GlyphSeries.test.tsx | import React, { useContext, useEffect } from 'react';
import { render } from '@testing-library/react';
import '@testing-library/jest-dom';
import { AnimatedGlyphSeries, DataContext, GlyphSeries, useEventEmitter } from '../../src';
import getDataContext from '../mocks/getDataContext';
import setupTooltipTest from '../mocks/setupTooltipTest';
import { XYCHART_EVENT_SOURCE } from '../../src/constants';
const series = { key: 'glyph', data: [{}, {}], xAccessor: () => 4, yAccessor: () => 7 };
const seriesMissingData = {
key: 'barMissingData',
data: [{ x: 1 }, { x: 0, y: 3 }, { y: 2 }],
xAccessor: (d: { x?: number }) => d.x,
yAccessor: (d: { y?: number }) => d.y,
};
describe('<GlyphSeries />', () => {
it('should be defined', () => {
expect(GlyphSeries).toBeDefined();
});
it('should render a DefaultGlyph for each Datum', () => {
const { container } = render(
<DataContext.Provider value={getDataContext(series)}>
<svg>
<GlyphSeries dataKey={series.key} {...series} />
</svg>
</DataContext.Provider>,
);
expect(container.querySelectorAll('circle')).toHaveLength(series.data.length);
});
it('should use colorAccessor if passed', () => {
const { container } = render(
<DataContext.Provider value={getDataContext(series)}>
<svg>
<GlyphSeries
dataKey={series.key}
{...series}
colorAccessor={(_, i) => (i === 0 ? 'banana' : null)}
/>
</svg>
</DataContext.Provider>,
);
const circles = container.querySelectorAll('circle');
expect(circles[0]).toHaveAttribute('fill', 'banana');
expect(circles[1]).not.toHaveAttribute('fill', 'banana');
});
it('should not render Glyphs if x or y is invalid', () => {
const { container } = render(
<DataContext.Provider value={getDataContext(seriesMissingData)}>
<svg>
<GlyphSeries dataKey={seriesMissingData.key} {...seriesMissingData} />
</svg>
</DataContext.Provider>,
);
expect(container.querySelectorAll('circle')).toHaveLength(1);
});
it('should render a custom Glyph for each Datum', () => {
const customRenderGlyph = () => <rect className="custom-glyph" />;
const { container } = render(
<DataContext.Provider value={getDataContext(series)}>
<svg>
<GlyphSeries dataKey={series.key} {...series} renderGlyph={customRenderGlyph} />
</svg>
</DataContext.Provider>,
);
expect(container.querySelectorAll('.custom-glyph')).toHaveLength(series.data.length);
});
it('should invoke showTooltip/hideTooltip on pointermove/pointerout', () => {
expect.assertions(2);
const showTooltip = jest.fn();
const hideTooltip = jest.fn();
const EventEmitter = () => {
const emit = useEventEmitter();
useEffect(() => {
if (emit) {
// not a React.MouseEvent
emit('pointermove', new MouseEvent('pointermove'), XYCHART_EVENT_SOURCE);
expect(showTooltip).toHaveBeenCalledTimes(1);
// not a React.MouseEvent
emit('pointerout', new MouseEvent('pointerout'), XYCHART_EVENT_SOURCE);
expect(showTooltip).toHaveBeenCalledTimes(1);
}
});
return null;
};
const ConditionalEventEmitter = () => {
const { dataRegistry } = useContext(DataContext);
// GlyphSeries won't render until its data is registered
// wait for that to emit the events
return dataRegistry?.get(series.key) ? <EventEmitter /> : null;
};
setupTooltipTest(
<>
<GlyphSeries dataKey={series.key} {...series} />
<ConditionalEventEmitter />
</>,
{ showTooltip, hideTooltip },
);
});
});
describe('<AnimatedGlyphSeries />', () => {
it('should be defined', () => {
expect(AnimatedGlyphSeries).toBeDefined();
});
it('should render an animated.g for each datum', () => {
const { container } = render(
<DataContext.Provider value={getDataContext(series)}>
<svg>
<AnimatedGlyphSeries dataKey={series.key} {...series} />
</svg>
</DataContext.Provider>,
);
expect(container.querySelectorAll('g')).toHaveLength(series.data.length);
});
});
|
8,291 | 0 | petrpan-code/airbnb/visx/packages/visx-xychart/test | petrpan-code/airbnb/visx/packages/visx-xychart/test/components/Grid.test.tsx | import * as React from 'react';
import { render } from '@testing-library/react';
import { Grid, AnimatedGrid, DataContext } from '../../src';
import getDataContext from '../mocks/getDataContext';
const mockContext = getDataContext();
describe('<Grid />', () => {
it('should be defined', () => {
expect(Grid).toBeDefined();
});
it('should render VxGridRows if rows=true', () => {
const { container } = render(
<DataContext.Provider value={mockContext}>
<svg>
<Grid rows columns={false} />
</svg>
</DataContext.Provider>,
);
expect(container.querySelectorAll('.visx-rows')).toHaveLength(1);
expect(container.querySelectorAll('.visx-columns')).toHaveLength(0);
});
it('should render VxGridColumns if columns=true', () => {
const { container } = render(
<DataContext.Provider value={mockContext}>
<svg>
<Grid rows={false} columns />
</svg>
</DataContext.Provider>,
);
expect(container.querySelectorAll('.visx-rows')).toHaveLength(0);
expect(container.querySelectorAll('.visx-columns')).toHaveLength(1);
});
});
describe('<AnimatedGrid />', () => {
it('should be defined', () => {
expect(AnimatedGrid).toBeDefined();
});
it('should render VxAnimatedGridRows if rows=true', () => {
const { container } = render(
<DataContext.Provider value={mockContext}>
<svg>
<AnimatedGrid rows columns={false} />
</svg>
</DataContext.Provider>,
);
expect(container.querySelectorAll('.visx-rows')).toHaveLength(1);
expect(container.querySelectorAll('.visx-columns')).toHaveLength(0);
});
it('should render VxAnimatedGridColumns if columns=true', () => {
const { container } = render(
<DataContext.Provider value={mockContext}>
<svg>
<AnimatedGrid rows={false} columns />
</svg>
</DataContext.Provider>,
);
expect(container.querySelectorAll('.visx-rows')).toHaveLength(0);
expect(container.querySelectorAll('.visx-columns')).toHaveLength(1);
});
});
|
8,292 | 0 | petrpan-code/airbnb/visx/packages/visx-xychart/test | petrpan-code/airbnb/visx/packages/visx-xychart/test/components/LineSeries.test.tsx | import React, { useContext, useEffect } from 'react';
import { render } from '@testing-library/react';
import '@testing-library/jest-dom';
import { AnimatedLineSeries, DataContext, LineSeries, useEventEmitter } from '../../src';
import getDataContext from '../mocks/getDataContext';
import setupTooltipTest from '../mocks/setupTooltipTest';
import { XYCHART_EVENT_SOURCE } from '../../src/constants';
const series = { key: 'line', data: [{}], xAccessor: () => 4, yAccessor: () => 7 };
describe('<LineSeries />', () => {
it('should be defined', () => {
expect(LineSeries).toBeDefined();
});
it('should render a LinePath', () => {
const { container } = render(
<DataContext.Provider value={getDataContext(series)}>
<svg>
<LineSeries dataKey={series.key} {...series} />
</svg>
</DataContext.Provider>,
);
expect(container.querySelectorAll('path')).toHaveLength(1);
});
it('should set strokeLinecap="round" to make datum surrounded by nulls visible', () => {
const { container } = render(
<DataContext.Provider value={getDataContext(series)}>
<svg>
<LineSeries dataKey={series.key} {...series} />
</svg>
</DataContext.Provider>,
);
expect(container.querySelector('path')).toHaveAttribute('stroke-linecap', 'round');
});
it('should render Glyphs if focus/blur handlers are set', () => {
const { container } = render(
<DataContext.Provider value={getDataContext(series)}>
<svg>
<LineSeries dataKey={series.key} {...series} onFocus={() => {}} />
</svg>
</DataContext.Provider>,
);
expect(container.querySelectorAll('circle')).toHaveLength(series.data.length);
});
it('should invoke showTooltip/hideTooltip on pointermove/pointerout', () => {
expect.assertions(2);
const showTooltip = jest.fn();
const hideTooltip = jest.fn();
const EventEmitter = () => {
const emit = useEventEmitter();
useEffect(() => {
if (emit) {
// not a React.MouseEvent
emit('pointermove', new MouseEvent('pointermove'), XYCHART_EVENT_SOURCE);
expect(showTooltip).toHaveBeenCalledTimes(1);
// not a React.MouseEvent
emit('pointerout', new MouseEvent('pointerout'), XYCHART_EVENT_SOURCE);
expect(showTooltip).toHaveBeenCalledTimes(1);
}
});
return null;
};
const ConditionalEventEmitter = () => {
const { dataRegistry } = useContext(DataContext);
// LineSeries won't render until its data is registered
// wait for that to emit the events
return dataRegistry?.get(series.key) ? <EventEmitter /> : null;
};
setupTooltipTest(
<>
<LineSeries dataKey={series.key} {...series} />
<ConditionalEventEmitter />
</>,
{ showTooltip, hideTooltip },
);
});
it('should use colorAccessor if passed', () => {
const { container } = render(
<DataContext.Provider value={getDataContext(series)}>
<svg>
<LineSeries dataKey={series.key} {...series} colorAccessor={(_) => 'banana'} />
</svg>
</DataContext.Provider>,
);
expect(container.querySelector('path')).toHaveAttribute('stroke', 'banana');
});
});
describe('<AnimatedLineSeries />', () => {
it('should be defined', () => {
expect(AnimatedLineSeries).toBeDefined();
});
it('should render an animated.path', () => {
const { container } = render(
<DataContext.Provider value={getDataContext(series)}>
<svg>
<AnimatedLineSeries dataKey={series.key} {...series} />
</svg>
</DataContext.Provider>,
);
expect(container.querySelectorAll('path')).toHaveLength(1);
});
});
|
8,293 | 0 | petrpan-code/airbnb/visx/packages/visx-xychart/test | petrpan-code/airbnb/visx/packages/visx-xychart/test/components/Tooltip.test.tsx | import React from 'react';
import { ResizeObserver } from '@juggle/resize-observer';
import { render } from '@testing-library/react';
import '@testing-library/jest-dom';
import { AnyD3Scale } from '@visx/scale';
import {
DataContext,
DataRegistryEntry,
Tooltip,
TooltipContext,
TooltipContextType,
} from '../../src';
import { TooltipProps } from '../../src/components/Tooltip';
import getDataContext from '../mocks/getDataContext';
describe('<Tooltip />', () => {
type SetupProps =
| {
props?: Partial<TooltipProps<object>>;
context?: Partial<TooltipContextType<object>>;
dataEntries?: DataRegistryEntry<AnyD3Scale, AnyD3Scale, {}>[];
}
| undefined;
function setup({ props, context, dataEntries = [] }: SetupProps = {}) {
// Disable Warning: render(): Rendering components directly into document.body is discouraged.
const wrapper = render(
<DataContext.Provider
value={{
...getDataContext(dataEntries),
}}
>
<TooltipContext.Provider
value={{
tooltipOpen: false,
showTooltip: jest.fn(),
updateTooltip: jest.fn(),
hideTooltip: jest.fn(),
...context,
}}
>
<Tooltip
resizeObserverPolyfill={ResizeObserver}
renderTooltip={() => <div />}
{...props}
/>
</TooltipContext.Provider>
</DataContext.Provider>,
);
return wrapper;
}
it('should be defined', () => {
expect(Tooltip).toBeDefined();
});
it('should not render a BaseTooltip when TooltipContext.tooltipOpen=false', () => {
const { container } = setup();
expect(container?.parentNode?.querySelectorAll('.visx-tooltip')).toHaveLength(0);
});
it('should not render a BaseTooltip when TooltipContext.tooltipOpen=true and renderTooltip returns false', () => {
const { container } = setup({
context: { tooltipOpen: true },
props: { renderTooltip: () => null },
});
expect(container?.parentNode?.querySelectorAll('.visx-tooltip')).toHaveLength(0);
});
it('should render a BaseTooltip when TooltipContext.tooltipOpen=true and renderTooltip returns non-null', () => {
const { container } = setup({
props: { renderTooltip: () => <div />, snapTooltipToDatumX: true },
context: { tooltipOpen: true },
});
expect(container?.parentNode?.querySelectorAll('.visx-tooltip')).toHaveLength(1);
});
it('should not invoke props.renderTooltip when TooltipContext.tooltipOpen=false', () => {
const renderTooltip = jest.fn(() => <div />);
setup({
props: { renderTooltip },
});
expect(renderTooltip).toHaveBeenCalledTimes(0);
});
it('should invoke props.renderTooltip when TooltipContext.tooltipOpen=true', () => {
const renderTooltip = jest.fn(() => <div />);
setup({
props: { renderTooltip },
context: { tooltipOpen: true },
});
expect(renderTooltip).toHaveBeenCalled(); // may be invoked more than once due to forceRefreshBounds invocation
});
it('should render a vertical crosshair if showVerticalCrossHair=true', () => {
const { container } = setup({
props: { showVerticalCrosshair: true },
context: { tooltipOpen: true },
});
expect(container?.parentNode?.querySelectorAll('div.visx-crosshair-vertical')).toHaveLength(1);
});
it('should render a horizontal crosshair if showVerticalCrossHair=true', () => {
const { container } = setup({
props: { showHorizontalCrosshair: true },
context: { tooltipOpen: true },
});
expect(container?.parentNode?.querySelectorAll('div.visx-crosshair-horizontal')).toHaveLength(
1,
);
});
it('should not render a glyph if showDatumGlyph=true and there is no nearestDatum', () => {
const { container } = setup({
props: { showDatumGlyph: true },
context: {
tooltipOpen: true,
tooltipData: {
datumByKey: {},
},
},
dataEntries: [
{
key: 'd1',
xAccessor: () => 3,
yAccessor: () => 7,
data: [{}],
},
],
});
expect(container?.parentNode?.querySelectorAll('div.visx-tooltip-glyph')).toHaveLength(0);
});
it('should render a glyph if showDatumGlyph=true if there is a nearestDatum', () => {
const { container } = setup({
props: { showDatumGlyph: true },
context: {
tooltipOpen: true,
tooltipData: {
nearestDatum: { distance: 1, key: 'd1', index: 0, datum: {} },
datumByKey: {},
},
},
dataEntries: [
{
key: 'd1',
xAccessor: () => 3,
yAccessor: () => 7,
data: [{}],
},
],
});
expect(container?.parentNode?.querySelectorAll('.visx-tooltip-glyph')).toHaveLength(1);
});
it('should render a glyph for each series if showSeriesGlyphs=true', () => {
const { container } = setup({
props: { showSeriesGlyphs: true },
context: {
tooltipOpen: true,
tooltipData: {
datumByKey: {
d1: { key: 'd1', index: 0, datum: {} },
d2: { key: 'd2', index: 1, datum: {} },
},
},
},
dataEntries: [
{
key: 'd1',
xAccessor: () => 3,
yAccessor: () => 7,
data: [{}],
},
{
key: 'd2',
xAccessor: () => 3,
yAccessor: () => 7,
data: [{}],
},
],
});
expect(container?.parentNode?.querySelectorAll('div.visx-tooltip-glyph')).toHaveLength(2);
});
it('should pass zIndex prop to Portal', () => {
const { container } = setup({
props: { zIndex: 123 },
context: { tooltipOpen: true },
});
const zIndex =
container?.parentNode?.querySelector('div.visx-tooltip')?.parentElement?.style.zIndex;
expect(zIndex).toBe('123');
});
});
|
8,294 | 0 | petrpan-code/airbnb/visx/packages/visx-xychart/test | petrpan-code/airbnb/visx/packages/visx-xychart/test/components/XYChart.test.tsx | import React, { useContext } from 'react';
import { mount } from 'enzyme';
import { ResizeObserver } from '@juggle/resize-observer';
import { render } from '@testing-library/react';
import '@testing-library/jest-dom';
import { XYChart, DataProvider, DataContext } from '../../src';
const chartProps = {
xScale: { type: 'linear' },
yScale: { type: 'linear' },
width: 100,
height: 100,
} as const;
describe('<XYChart />', () => {
let initialResizeObserver: typeof ResizeObserver;
beforeAll(() => {
// don't worry about passing it via context
initialResizeObserver = window.ResizeObserver;
window.ResizeObserver = ResizeObserver;
});
afterAll(() => {
window.ResizeObserver = initialResizeObserver;
});
it('should be defined', () => {
expect(XYChart).toBeDefined();
});
it('should render with parent size if width or height is not provided', () => {
const { getByTestId } = render(
<div style={{ width: '200px', height: '200px' }} data-testid="wrapper">
<XYChart {...chartProps} width={undefined} data-testid="rect">
<rect />
</XYChart>
</div>,
);
// the XYChart should auto-resize to it's parent size
const Wrapper = getByTestId('wrapper');
expect(Wrapper.firstChild).toHaveStyle('width: 100%; height: 100%');
});
it('should warn if DataProvider is not available and no x- or yScale config is passed', () => {
expect(() =>
mount(
<XYChart>
<rect />
</XYChart>,
),
).toThrow();
});
it('should render an svg', () => {
const { container } = render(
<XYChart {...chartProps}>
<rect />
</XYChart>,
);
const SVGElement = container.querySelector('svg');
expect(SVGElement).toBeDefined();
});
it('should render children', () => {
const { container } = render(
<XYChart {...chartProps}>
<rect id="xychart-child" />
</XYChart>,
);
const XYChartChild = container.querySelector('#xychart-child');
expect(XYChartChild).toBeDefined();
});
it('should update the registry dimensions', () => {
expect.assertions(2);
const width = 123;
const height = 456;
const DataConsumer = () => {
const data = useContext(DataContext);
// eslint-disable-next-line jest/no-if
if (data.width && data.height) {
expect(data.width).toBe(width);
expect(data.height).toBe(height);
}
return null;
};
render(
<DataProvider xScale={{ type: 'linear' }} yScale={{ type: 'linear' }}>
<XYChart width={width} height={height}>
<DataConsumer />
</XYChart>
</DataProvider>,
);
});
});
|
8,295 | 0 | petrpan-code/airbnb/visx/packages/visx-xychart/test | petrpan-code/airbnb/visx/packages/visx-xychart/test/enhancers/withRegisteredData.test.tsx | /* eslint-disable @typescript-eslint/no-explicit-any */
import React from 'react';
import { render } from '@testing-library/react';
import '@testing-library/jest-dom';
import withRegisteredData from '../../src/enhancers/withRegisteredData';
import getDataContext from '../mocks/getDataContext';
import { DataContext } from '../../src';
const series = {
key: 'visx',
xAccessor: () => 'x',
yAccessor: () => 'y',
data: [{}],
};
describe('withRegisteredData', () => {
it('should be defined', () => {
expect(withRegisteredData).toBeDefined();
});
it('should return a component', () => {
const BaseComponent = () => <div />;
const WrappedComponent = withRegisteredData(BaseComponent);
expect(() => <WrappedComponent dataKey={series.key} {...series} />).not.toThrow();
});
it('should not render base component if scales or key is not in context', () => {
const mockContextWithSeries = getDataContext(series);
const BaseComponent = () => <div />;
const WrappedComponent = withRegisteredData(BaseComponent);
const { container: containerNoContext } = render(
<DataContext.Provider value={{}}>
<WrappedComponent dataKey={series.key} {...series} />
</DataContext.Provider>,
);
const { container: containerCompleteContext } = render(
<DataContext.Provider value={mockContextWithSeries}>
<WrappedComponent dataKey={series.key} {...series} />
</DataContext.Provider>,
);
expect(containerNoContext.querySelectorAll('div')).toHaveLength(0);
expect(containerCompleteContext.querySelectorAll('div')).toHaveLength(1);
});
it('should pass data and accessors to BaseComponent from context not props', () => {
expect.assertions(3);
const mockContext = getDataContext(series);
const BaseComponent = ({ data, xAccessor, yAccessor }: any) => {
expect(data).toBe(series.data);
expect(xAccessor).toBe(series.xAccessor);
expect(yAccessor).toBe(series.yAccessor);
return null;
};
const WrappedComponent = withRegisteredData(BaseComponent);
render(
<DataContext.Provider value={mockContext}>
<WrappedComponent
dataKey={series.key}
{...series}
data={[]}
xAccessor={() => 3}
yAccessor={() => 4}
/>
</DataContext.Provider>,
);
});
});
|
8,296 | 0 | petrpan-code/airbnb/visx/packages/visx-xychart/test | petrpan-code/airbnb/visx/packages/visx-xychart/test/hooks/useDataRegistry.test.tsx | import React from 'react';
import { render } from '@testing-library/react';
import useDataRegistry from '../../src/hooks/useDataRegistry';
describe('useDataRegistry', () => {
it('should be defined', () => {
expect(useDataRegistry).toBeDefined();
});
it('should provide a DataRegistry', () => {
expect.assertions(1);
const RegistryConsumer = () => {
const registry = useDataRegistry();
expect(registry).toBeDefined();
return null;
};
render(<RegistryConsumer />);
});
});
|
8,297 | 0 | petrpan-code/airbnb/visx/packages/visx-xychart/test | petrpan-code/airbnb/visx/packages/visx-xychart/test/hooks/useEventEmitter.test.tsx | import React, { useEffect } from 'react';
import { render } from '@testing-library/react';
import useEventEmitter from '../../src/hooks/useEventEmitter';
import { EventEmitterProvider } from '../../src';
// avoids a lot of coercing of types
const getEvent = (eventType: string) => new MouseEvent(eventType) as unknown as React.PointerEvent;
describe('useEventEmitter', () => {
it('should be defined', () => {
expect(useEventEmitter).toBeDefined();
});
it('should provide an emitter', () => {
expect.assertions(1);
const Component = () => {
const emitter = useEventEmitter();
expect(emitter).toEqual(expect.any(Function));
return null;
};
render(
<EventEmitterProvider>
<Component />
</EventEmitterProvider>,
);
});
it('should register event listeners and emit events', () => {
expect.assertions(1);
const Component = () => {
const listener = jest.fn();
const emit = useEventEmitter('pointermove', listener);
useEffect(() => {
if (emit) {
emit('pointermove', getEvent('pointermove'));
expect(listener).toHaveBeenCalledTimes(1);
}
});
return null;
};
render(
<EventEmitterProvider>
<Component />
</EventEmitterProvider>,
);
});
it('should filter invalid sources if specified', () => {
expect.assertions(4);
const Component = () => {
const eventType = 'pointermove';
const sourceId = 'sourceId';
const listener = jest.fn();
const filteredListener = jest.fn();
const emit = useEventEmitter();
useEventEmitter('pointermove', listener);
useEventEmitter('pointermove', filteredListener, [sourceId]);
useEffect(() => {
if (emit) {
emit(eventType, getEvent(eventType));
expect(listener).toHaveBeenCalledTimes(1);
expect(filteredListener).toHaveBeenCalledTimes(0);
emit(eventType, getEvent(eventType), sourceId);
expect(listener).toHaveBeenCalledTimes(2);
expect(filteredListener).toHaveBeenCalledTimes(1);
}
});
return null;
};
render(
<EventEmitterProvider>
<Component />
</EventEmitterProvider>,
);
});
});
|
8,298 | 0 | petrpan-code/airbnb/visx/packages/visx-xychart/test | petrpan-code/airbnb/visx/packages/visx-xychart/test/hooks/useEventEmitters.test.tsx | import React, { useEffect } from 'react';
import { render } from '@testing-library/react';
import { EventEmitterProvider, useEventEmitter } from '../../src';
import useEventEmitters from '../../src/hooks/useEventEmitters';
describe('useEventEmitters', () => {
it('should be defined', () => {
expect(useEventEmitters).toBeDefined();
});
it('should provide an emitter for each callback specified', () => {
expect.assertions(1);
const Component = () => {
const emitters = useEventEmitters({
source: 'visx',
onPointerOut: false,
onBlur: true,
onFocus: true,
});
expect(emitters).toEqual({
onBlur: expect.any(Function),
onFocus: expect.any(Function),
onPointerMove: expect.any(Function),
onPointerOut: undefined,
onPointerUp: expect.any(Function),
onPointerDown: expect.any(Function),
});
return null;
};
render(
<EventEmitterProvider>
<Component />
</EventEmitterProvider>,
);
});
it('emitters should emit events', () => {
expect.assertions(1);
const Component = () => {
const source = 'sourceId';
const listener = jest.fn();
useEventEmitter('pointerup', listener, [source]);
const emitters = useEventEmitters({ source });
useEffect(() => {
if (emitters.onPointerUp) {
emitters.onPointerUp(new MouseEvent('pointerup') as unknown as React.PointerEvent);
expect(listener).toHaveBeenCalledTimes(1);
}
});
return null;
};
render(
<EventEmitterProvider>
<Component />
</EventEmitterProvider>,
);
});
});
|
8,299 | 0 | petrpan-code/airbnb/visx/packages/visx-xychart/test | petrpan-code/airbnb/visx/packages/visx-xychart/test/hooks/useEventHandlers.test.tsx | import React, { useEffect } from 'react';
import { render } from '@testing-library/react';
import { EventEmitterProvider, useEventEmitter, DataContext } from '../../src';
import useEventHandlers, { POINTER_EVENTS_ALL } from '../../src/hooks/useEventHandlers';
import getDataContext from '../mocks/getDataContext';
const series1 = { key: 'series1', data: [{}], xAccessor: () => 4, yAccessor: () => 7 };
const series2 = { key: 'series2', data: [{}], xAccessor: () => 4, yAccessor: () => 7 };
// avoids a lot of coercing of types
const getEvent = (eventType: string) => new MouseEvent(eventType) as unknown as React.PointerEvent;
describe('useEventHandlers', () => {
function setup(children: React.ReactNode) {
return render(
<DataContext.Provider value={getDataContext([series1, series2])}>
<EventEmitterProvider>{children}</EventEmitterProvider>
</DataContext.Provider>,
);
}
it('should be defined', () => {
expect(useEventHandlers).toBeDefined();
});
it('should invoke handlers for each pointer event handler specified', () => {
expect.assertions(5);
const Component = () => {
const sourceId = 'sourceId';
const pointerMoveListener = jest.fn();
const pointerOutListener = jest.fn();
const pointerUpListener = jest.fn();
const focusListener = jest.fn();
const blurListener = jest.fn();
const emit = useEventEmitter();
useEventHandlers({
allowedSources: [sourceId],
dataKey: series1.key,
onFocus: focusListener,
onBlur: blurListener,
onPointerMove: pointerMoveListener,
onPointerOut: pointerOutListener,
onPointerUp: pointerUpListener,
});
useEffect(() => {
if (emit) {
emit('pointermove', getEvent('pointermove'), sourceId);
emit('pointermove', getEvent('pointermove'), 'invalidSource');
expect(pointerMoveListener).toHaveBeenCalledTimes(1);
emit('pointerout', getEvent('pointerout'), sourceId);
emit('pointerout', getEvent('pointerout'), 'invalidSource');
expect(pointerOutListener).toHaveBeenCalledTimes(1);
emit('pointerup', getEvent('pointerup'), sourceId);
emit('pointerup', getEvent('pointerup'), 'invalidSource');
expect(pointerUpListener).toHaveBeenCalledTimes(1);
emit('focus', new FocusEvent('focus') as unknown as React.FocusEvent, sourceId);
emit('focus', new FocusEvent('focus') as unknown as React.FocusEvent, 'invalidSource');
expect(focusListener).toHaveBeenCalledTimes(1);
emit('blur', new FocusEvent('blur') as unknown as React.FocusEvent, sourceId);
emit('blur', new FocusEvent('blur') as unknown as React.FocusEvent, 'invalidSource');
expect(blurListener).toHaveBeenCalledTimes(1);
}
});
return null;
};
setup(<Component />);
});
it('should invoke handlers once for each dataKey specified', () => {
expect.assertions(4);
const Component = () => {
const sourceId = 'sourceId';
const pointerMoveListenerAll = jest.fn();
const pointerMoveListenerMultipleKeys = jest.fn();
const emit = useEventEmitter();
useEventHandlers({
allowedSources: [sourceId],
dataKey: POINTER_EVENTS_ALL,
onPointerMove: pointerMoveListenerAll,
});
useEventHandlers({
allowedSources: [sourceId],
dataKey: [series1.key, series2.key],
onPointerMove: pointerMoveListenerMultipleKeys,
});
useEffect(() => {
if (emit) {
emit('pointermove', getEvent('pointermove'), sourceId);
expect(pointerMoveListenerAll).toHaveBeenCalledTimes(2);
expect(pointerMoveListenerMultipleKeys).toHaveBeenCalledTimes(2);
emit('pointermove', getEvent('pointermove'), 'invalidSource');
expect(pointerMoveListenerAll).toHaveBeenCalledTimes(2);
expect(pointerMoveListenerMultipleKeys).toHaveBeenCalledTimes(2);
}
});
return null;
};
setup(<Component />);
});
});
|
8,300 | 0 | petrpan-code/airbnb/visx/packages/visx-xychart/test | petrpan-code/airbnb/visx/packages/visx-xychart/test/hooks/useScales.test.tsx | import useScales from '../../src/hooks/useScales';
describe('useScales', () => {
it('should be defined', () => {
expect(useScales).toBeDefined();
});
});
|
8,301 | 0 | petrpan-code/airbnb/visx/packages/visx-xychart/test | petrpan-code/airbnb/visx/packages/visx-xychart/test/hooks/useStackedData.test.tsx | import React, { useContext, useEffect } from 'react';
import { render } from '@testing-library/react';
import { AreaSeries, DataContext, DataProvider } from '../../src';
import useStackedData from '../../src/hooks/useStackedData';
const seriesAProps = {
dataKey: 'a',
data: [
{ x: 'stack-a', y: 3 },
{ x: 'stack-b', y: 7 },
{ x: 'stack-c', y: -2 },
],
xAccessor: (d: { x: string }) => d.x,
yAccessor: (d: { y: number }) => d.y,
};
const seriesBProps = {
...seriesAProps,
dataKey: 'b',
data: [
{ x: 'stack-a', y: 0 },
{ x: 'stack-b', y: 7 },
{ x: 'stack-c', y: 10 },
],
};
function setup(children: React.ReactElement | React.ReactElement[]) {
return render(
<DataProvider
initialDimensions={{ width: 10, height: 10 }}
xScale={{ type: 'band' }}
yScale={{ type: 'linear' }}
>
{children}
</DataProvider>,
);
}
describe('useStackedData', () => {
it('should be defined', () => {
expect(useStackedData).toBeDefined();
});
it('should return a data stack', () => {
expect.hasAssertions();
const Consumer = ({ children }: { children: React.ReactElement | React.ReactElement[] }) => {
const { stackedData } = useStackedData({ children });
// stackedData has arrays with data properties set by d3 which jest doesn't like
expect(stackedData.map((series) => series.map(([min, max]) => [min, max]))).toMatchObject([
[
// series a
[0, 3],
[0, 7],
[-2, 0],
],
[
// series b
[0, 0],
[7, 14],
[0, 10],
],
]);
return null;
};
setup(
<Consumer>
<AreaSeries {...seriesAProps} />
<AreaSeries {...seriesBProps} />
</Consumer>,
);
});
it('compute a comprehensive domain based on the total stack value', () => {
expect.hasAssertions();
const Consumer = ({ children }: { children: React.ReactElement | React.ReactElement[] }) => {
useStackedData({ children });
const { dataRegistry, yScale } = useContext(DataContext);
useEffect(() => {
if (dataRegistry?.get('a') && yScale) {
expect(yScale.domain()).toEqual([-2, 14]);
}
}, [dataRegistry, yScale]);
return null;
};
setup(
<Consumer>
<AreaSeries {...seriesAProps} />
<AreaSeries {...seriesBProps} />
</Consumer>,
);
});
});
|
8,304 | 0 | petrpan-code/airbnb/visx/packages/visx-xychart/test | petrpan-code/airbnb/visx/packages/visx-xychart/test/providers/DataProvider.test.tsx | import React, { useContext, useEffect } from 'react';
import { render } from '@testing-library/react';
import { DataProvider, DataContext } from '../../src';
import { DataProviderProps } from '../../lib/providers/DataProvider';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const getWrapper = (consumer: React.ReactNode, props?: DataProviderProps<any, any>) => {
render(
<DataProvider xScale={{ type: 'linear' }} yScale={{ type: 'linear' }} {...props}>
{consumer}
</DataProvider>,
);
};
describe('<DataProvider />', () => {
it('should be defined', () => {
expect(DataProvider).toBeDefined();
});
it('should provide a XYChartTheme', () => {
expect.assertions(1);
const DataConsumer = () => {
const data = useContext(DataContext);
expect(data.theme).toBeDefined();
return null;
};
getWrapper(<DataConsumer />);
});
it('should provide dimensions', () => {
expect.assertions(5);
const DataConsumer = () => {
const data = useContext(DataContext);
expect(data.width).toEqual(expect.any(Number));
expect(data.height).toEqual(expect.any(Number));
expect(data.innerWidth).toEqual(expect.any(Number));
expect(data.innerHeight).toEqual(expect.any(Number));
expect(data.margin).toMatchObject({
top: expect.any(Number),
right: expect.any(Number),
bottom: expect.any(Number),
left: expect.any(Number),
});
return null;
};
getWrapper(<DataConsumer />);
});
it('should provide scales', () => {
expect.assertions(3);
const DataConsumer = () => {
const { xScale, yScale, colorScale, registerData } = useContext(DataContext);
// some data needs to be registered for valid scales to be available
useEffect(() => {
if (registerData) {
registerData({
key: 'visx',
xAccessor: (d) => d.x,
yAccessor: (d) => d.y,
data: [
{ x: 0, y: 1 },
{ x: 5, y: 7 },
],
});
}
}, [registerData]);
useEffect(() => {
if (xScale && yScale && colorScale) {
expect(xScale).toBeDefined();
expect(yScale).toBeDefined();
expect(colorScale).toBeDefined();
}
}, [xScale, yScale, colorScale]);
return null;
};
getWrapper(<DataConsumer />);
});
});
|
8,305 | 0 | petrpan-code/airbnb/visx/packages/visx-xychart/test | petrpan-code/airbnb/visx/packages/visx-xychart/test/providers/EventEmitterProvider.test.tsx | import React, { useContext } from 'react';
import { render } from '@testing-library/react';
import { EventEmitterProvider, EventEmitterContext } from '../../src';
describe('<EventEmitterProvider />', () => {
it('should be defined', () => {
expect(EventEmitterProvider).toBeDefined();
});
it('should provide an emitter for subscribing and emitting events', () => {
expect.assertions(1);
const EventEmitterConsumer = () => {
const emitter = useContext(EventEmitterContext);
expect(emitter).toMatchObject({ on: expect.any(Function), emit: expect.any(Function) });
return null;
};
render(
<EventEmitterProvider>
<EventEmitterConsumer />
</EventEmitterProvider>,
);
});
});
|
8,306 | 0 | petrpan-code/airbnb/visx/packages/visx-xychart/test | petrpan-code/airbnb/visx/packages/visx-xychart/test/providers/ThemeProvider.test.tsx | import React, { useContext } from 'react';
import { render } from '@testing-library/react';
import { ThemeProvider, ThemeContext } from '../../src';
describe('<ThemeProvider />', () => {
it('should be defined', () => {
expect(ThemeProvider).toBeDefined();
});
it('should provide a XYChartTheme', () => {
expect.assertions(1);
const ThemeConsumer = () => {
const theme = useContext(ThemeContext);
expect(theme).toBeDefined();
return null;
};
render(
<ThemeProvider>
<ThemeConsumer />
</ThemeProvider>,
);
});
});
|
8,307 | 0 | petrpan-code/airbnb/visx/packages/visx-xychart/test | petrpan-code/airbnb/visx/packages/visx-xychart/test/providers/TooltipProvider.test.tsx | import React, { useContext, useEffect } from 'react';
import { render } from '@testing-library/react';
import { TooltipProvider, TooltipContext, TooltipData } from '../../src';
describe('<TooltipProvider />', () => {
it('should be defined', () => {
expect(TooltipProvider).toBeDefined();
});
it('should provide tooltip state', () => {
expect.assertions(1);
const TooltipConsumer = () => {
const tooltipContext = useContext(TooltipContext);
expect(tooltipContext).toMatchObject({
tooltipOpen: expect.any(Boolean),
showTooltip: expect.any(Function),
updateTooltip: expect.any(Function),
hideTooltip: expect.any(Function),
});
return null;
};
render(
<TooltipProvider>
<TooltipConsumer />
</TooltipProvider>,
);
});
it('showTooltip should update tooltipData.nearestDatum/datumByKey', () => {
expect.assertions(1);
const TooltipConsumer = () => {
const tooltipContext = useContext(TooltipContext);
const tooltipOpen = tooltipContext?.tooltipOpen;
const showTooltip = tooltipContext?.showTooltip;
useEffect(() => {
// this triggers a re-render of the component which triggers the assertion block
if (!tooltipOpen && showTooltip) {
showTooltip({
key: 'near',
index: 0,
distanceX: 0,
distanceY: 0,
datum: { hi: 'hello' },
});
showTooltip({
key: 'far',
index: 1,
datum: { good: 'bye' },
distanceX: NaN,
// no distance = Infinity
});
}
}, [tooltipOpen, showTooltip]);
if (tooltipOpen) {
expect(tooltipContext?.tooltipData).toMatchObject({
nearestDatum: { key: 'near', index: 0, distance: 0, datum: { hi: 'hello' } },
datumByKey: {
near: { key: 'near', index: 0, datum: { hi: 'hello' } },
far: { key: 'far', index: 1, datum: { good: 'bye' } },
},
} as TooltipData<object>);
}
return null;
};
render(
<TooltipProvider>
<TooltipConsumer />
</TooltipProvider>,
);
});
});
|
8,308 | 0 | petrpan-code/airbnb/visx/packages/visx-xychart/test | petrpan-code/airbnb/visx/packages/visx-xychart/test/utils/cleanColorString.test.ts | import { cleanColor } from '../../src/utils/cleanColorString';
describe('cleanColorString', () => {
describe('cleanColor', () => {
it('should be defined', () => {
expect(cleanColor).toBeDefined();
});
it('should return input color for non-url colors', () => {
expect(cleanColor('violet')).toBe('violet');
});
it('should return a neutral color for url-containing colors', () => {
expect(cleanColor('url(#id)')).not.toBe('url(#id)');
});
});
});
|
8,309 | 0 | petrpan-code/airbnb/visx/packages/visx-xychart/test | petrpan-code/airbnb/visx/packages/visx-xychart/test/utils/combineBarStackData.test.tsx | import React from 'react';
import { BarSeries } from '../../src';
import combineBarStackData from '../../src/utils/combineBarStackData';
const accessors = {
xAccessor: (d: { x: number }) => d.x,
yAccessor: (d: { y: number }) => d.y,
};
const series1 = {
dataKey: 'bar1',
data: [
{ x: 10, y: 5 },
{ x: 7, y: -5 },
],
...accessors,
};
const series2 = {
dataKey: 'bar2',
data: [
{ x: 10, y: 5 },
{ x: 7, y: 20 },
],
...accessors,
};
const seriesChildren = [
<BarSeries key={series1.dataKey} {...series1} />,
<BarSeries key={series2.dataKey} {...series2} />,
];
describe('combineBarStackData', () => {
it('should be defined', () => {
expect(combineBarStackData).toBeDefined();
});
it('should combine data by x stack value when horizontal=false', () => {
expect(combineBarStackData(seriesChildren)).toEqual([
{ stack: 7, bar1: -5, bar2: 20, positiveSum: 20, negativeSum: -5 },
{ stack: 10, bar1: 5, bar2: 5, positiveSum: 10, negativeSum: 0 },
]);
});
it('should combine data by y stack value when horizontal=true', () => {
expect(combineBarStackData(seriesChildren, true)).toEqual([
{ stack: 5, bar1: 10, bar2: 10, positiveSum: 20, negativeSum: 0 },
{ stack: 20, bar1: undefined, bar2: 7, positiveSum: 7, negativeSum: 0 },
{ stack: -5, bar1: 7, bar2: undefined, positiveSum: 7, negativeSum: 0 },
]);
});
});
|
8,310 | 0 | petrpan-code/airbnb/visx/packages/visx-xychart/test | petrpan-code/airbnb/visx/packages/visx-xychart/test/utils/findNearestDatum.test.ts | import { AxisScale } from '@visx/axis';
import { scaleBand, scaleLinear } from '@visx/scale';
import { PositionScale } from '@visx/shape/lib/types';
import findNearestDatumX from '../../src/utils/findNearestDatumX';
import findNearestDatumY from '../../src/utils/findNearestDatumY';
import findNearestDatumXY from '../../src/utils/findNearestDatumXY';
import findNearestDatumSingleDimension from '../../src/utils/findNearestDatumSingleDimension';
import findNearestStackDatum from '../../src/utils/findNearestStackDatum';
import findNearestGroupDatum from '../../src/utils/findNearestGroupDatum';
import { BarStackDatum, NearestDatumArgs } from '../../src';
type Datum = { xVal: number; yVal: string };
const params: NearestDatumArgs<AxisScale, AxisScale, Datum> = {
dataKey: 'visx',
width: 10,
height: 10,
point: { x: 3, y: 8 },
data: [
{ xVal: 0, yVal: '0' },
{ xVal: 8, yVal: '8' },
],
xAccessor: (d) => d.xVal,
yAccessor: (d) => d.yVal,
xScale: scaleLinear({ domain: [0, 10], range: [0, 10] }),
yScale: scaleBand({ domain: ['0', '8'], range: [0, 10] }),
};
describe('findNearestDatumX', () => {
it('should be defined', () => {
expect(findNearestDatumX).toBeDefined();
});
it('should find the nearest datum', () => {
expect(
findNearestDatumX({
...params,
})!.datum,
).toEqual({ xVal: 0, yVal: '0' });
});
});
describe('findNearestDatumY', () => {
it('should be defined', () => {
expect(findNearestDatumY).toBeDefined();
});
it('should find the nearest datum', () => {
expect(
findNearestDatumY({
...params,
})!.datum,
).toEqual({ xVal: 8, yVal: '8' });
});
});
describe('findNearestDatumXY', () => {
it('should be defined', () => {
expect(findNearestDatumXY).toBeDefined();
});
it('should find the nearest datum', () => {
expect(
findNearestDatumXY({
...params,
point: { x: 3, y: 3 },
})!.datum,
).toEqual({ xVal: 0, yVal: '0' });
});
});
describe('findNearestDatumSingleDimension', () => {
it('should be defined', () => {
expect(findNearestDatumSingleDimension).toBeDefined();
});
it('should find the nearest datum for scaleLinear', () => {
expect(
findNearestDatumSingleDimension({
scale: params.xScale,
accessor: params.xAccessor,
data: params.data,
scaledValue: 3,
})!.datum,
).toEqual({ xVal: 0, yVal: '0' });
expect(
findNearestDatumSingleDimension({
scale: params.xScale,
accessor: params.xAccessor,
data: params.data,
scaledValue: 7,
})!.datum,
).toEqual({ xVal: 8, yVal: '8' });
});
it('should find the nearest datum for scaleBand', () => {
expect(
findNearestDatumSingleDimension({
scale: params.yScale,
accessor: params.yAccessor,
data: params.data,
scaledValue: 3,
})!.datum,
).toEqual({ xVal: 0, yVal: '0' });
expect(
findNearestDatumSingleDimension({
scale: params.yScale,
accessor: params.yAccessor,
data: params.data,
scaledValue: 8,
})!.datum,
).toEqual({ xVal: 8, yVal: '8' });
});
});
describe('findNearestStackDatum', () => {
it('should be defined', () => {
expect(findNearestStackDatum).toBeDefined();
});
it('should find the nearest datum', () => {
const d1 = { yVal: '🍌' };
const d2 = { yVal: '🚀' };
expect(
findNearestStackDatum(
{
...params,
// type is not technically correct, but coerce for test
} as unknown as NearestDatumArgs<AxisScale, AxisScale, BarStackDatum<AxisScale, AxisScale>>,
[d1, d2],
true,
)!.datum,
).toEqual(d2); // nearest datum index=1
});
});
describe('findNearestGroupDatum', () => {
it('should be defined', () => {
expect(findNearestGroupDatum).toBeDefined();
});
it('should find the nearest datum', () => {
expect(
findNearestGroupDatum(
{
...params,
} as NearestDatumArgs<PositionScale, PositionScale, Datum>,
scaleBand({ domain: [params.dataKey], range: [0, 10] }),
)!.datum,
).toEqual({ xVal: 0, yVal: '0' }); // non-horizontal means nearest x value
});
it('should set distance to 0', () => {
expect(
findNearestGroupDatum(
{
...params,
} as NearestDatumArgs<PositionScale, PositionScale, Datum>,
scaleBand({ domain: [params.dataKey], range: [0, 10] }),
true,
)!.distanceY,
).toBe(0);
});
});
|
8,311 | 0 | petrpan-code/airbnb/visx/packages/visx-xychart/test | petrpan-code/airbnb/visx/packages/visx-xychart/test/utils/getScaleBaseline.test.ts | import { scaleLinear } from '@visx/scale';
import getScaleBaseline from '../../src/utils/getScaleBaseline';
describe('getScaleBaseline', () => {
it('should be defined', () => {
expect(getScaleBaseline).toBeDefined();
});
it('should work for ascending ranges', () => {
expect(
getScaleBaseline(
scaleLinear({
domain: [0, 100],
range: [50, 100],
}),
),
).toBe(50);
});
it('should work for descending ranges', () => {
expect(
getScaleBaseline(
scaleLinear({
domain: [0, 100],
range: [100, 50],
}),
),
).toBe(100);
});
it("should use a scale's minimum even if its not clamped to exclude zero", () => {
expect(
getScaleBaseline(
scaleLinear({
domain: [100, 200],
range: [50, 100], // ascending
}),
),
).toBe(50);
expect(
getScaleBaseline(
scaleLinear({
domain: [100, 200],
range: [100, 50], // descending
}),
),
).toBe(100);
});
});
|
8,312 | 0 | petrpan-code/airbnb/visx/packages/visx-xychart/test | petrpan-code/airbnb/visx/packages/visx-xychart/test/utils/isDiscreteScale.test.ts | import isDiscreteScale from '../../src/utils/isDiscreteScale';
describe('isDiscreteScale', () => {
it('should be defined', () => {
expect(isDiscreteScale).toBeDefined();
});
it('should return true for discrete scales', () => {
expect(isDiscreteScale({ type: 'band' })).toBe(true);
expect(isDiscreteScale({ type: 'point' })).toBe(true);
expect(isDiscreteScale({ type: 'ordinal' })).toBe(true);
});
it('should return false for non-discrete scales', () => {
expect(isDiscreteScale({ type: 'time' })).toBe(false);
expect(isDiscreteScale({ type: 'utc' })).toBe(false);
expect(isDiscreteScale({ type: 'log' })).toBe(false);
expect(isDiscreteScale({ type: 'linear' })).toBe(false);
});
});
|
8,321 | 0 | petrpan-code/airbnb/visx/packages/visx-zoom | petrpan-code/airbnb/visx/packages/visx-zoom/test/Zoom.test.tsx | import React from 'react';
import { render } from 'enzyme';
import { Zoom, inverseMatrix } from '../src';
describe('<Zoom />', () => {
it('should be defined', () => {
expect(Zoom).toBeDefined();
});
it('should render the children and pass zoom params', () => {
const initialTransform = {
scaleX: 1.27,
scaleY: 1.27,
translateX: -211.62,
translateY: 162.59,
skewX: 0,
skewY: 0,
};
const wrapper = render(
<Zoom
width={400}
height={400}
scaleXMin={1 / 2}
scaleXMax={4}
scaleYMin={1 / 2}
scaleYMax={4}
initialTransformMatrix={initialTransform}
>
{({ transformMatrix }) => {
const { scaleX, scaleY, translateX, translateY } = transformMatrix;
return <div>{[scaleX, scaleY, translateX, translateY].join(',')}</div>;
}}
</Zoom>,
);
expect(wrapper.html()).toBe('1.27,1.27,-211.62,162.59');
});
});
describe('inverseMatrix', () => {
it('should be defined', () => {
expect(inverseMatrix).toBeDefined();
});
});
|
8,322 | 0 | petrpan-code/airbnb/visx/packages/visx-zoom | petrpan-code/airbnb/visx/packages/visx-zoom/test/tsconfig.json | {
"compilerOptions": {
"composite": false,
"emitDeclarationOnly": false,
"noEmit": true,
"rootDir": "."
},
"extends": "../../../tsconfig.options.json",
"include": ["**/*", "../types/**/*", "../../../types/**/*"],
"references": [
{
"path": ".."
}
]
}
|
9,130 | 0 | petrpan-code/alibaba/ice/examples | petrpan-code/alibaba/ice/examples/with-vitest/tsconfig.json | {
"compileOnSave": false,
"buildOnSave": false,
"compilerOptions": {
"baseUrl": ".",
"outDir": "build",
"module": "esnext",
"target": "es6",
"jsx": "react-jsx",
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"lib": ["es6", "dom"],
"sourceMap": true,
"allowJs": true,
"rootDir": "./",
"forceConsistentCasingInFileNames": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noImplicitAny": false,
"importHelpers": true,
"strictNullChecks": true,
"suppressImplicitAnyIndexErrors": true,
"noUnusedLocals": true,
"skipLibCheck": true,
"paths": {
"@/*": ["./src/*"],
"ice": [".ice"]
}
},
"include": ["src", ".ice", "ice.config.*", "tests", "./vitest-setup.ts"],
"exclude": ["node_modules", "build", "public"]
} |
9,161 | 0 | petrpan-code/alibaba/ice/packages/appear | petrpan-code/alibaba/ice/packages/appear/tests/visibilityChange.test.tsx | /**
* @vitest-environment jsdom
*/
import { it, describe } from 'vitest';
import { render } from '@testing-library/react';
import React from 'react';
import VisibilityChange from '../src/index';
describe('visibilytyChange', () => {
it('appear', () => {
return new Promise(resolve => {
function App() {
return (<VisibilityChange
onAppear={() => {
resolve(true);
}}
>
<span>content</span>
</VisibilityChange>);
}
render(<App />);
});
});
it('child shold work with ref', () => {
return new Promise(resolve => {
function App() {
const ref = React.useRef(null);
React.useEffect(() => {
if (ref) {
resolve(true);
}
}, [ref]);
return (<VisibilityChange
onAppear={() => {
}}
>
<span>content</span>
</VisibilityChange>);
}
render(<App />);
});
});
});
|
9,239 | 0 | petrpan-code/alibaba/ice/packages/ice/src | petrpan-code/alibaba/ice/packages/ice/src/commands/test.ts | import type { Context, TaskConfig } from 'build-scripts';
import type { Config } from '@ice/shared-config/types';
import type ora from '@ice/bundles/compiled/ora/index.js';
function test(
context: Context<Config>,
options: {
taskConfigs: TaskConfig<Config>[];
spinner: ora.Ora;
},
) {
const { taskConfigs, spinner } = options;
spinner.stop();
return {
taskConfigs,
context,
};
}
export default test;
|
9,319 | 0 | petrpan-code/alibaba/ice/packages/ice | petrpan-code/alibaba/ice/packages/ice/tests/defineJestConfig.test.ts | import * as path from 'path';
import { fileURLToPath } from 'url';
import { expect, it, describe, vi, beforeAll } from 'vitest';
import { defineJestConfig } from '../src/test';
const __dirname = fileURLToPath(path.dirname(import.meta.url));
describe('defineJestConfig', () => {
const builtInAlias = [
'^ice',
'^ice/types',
'^@/(.*)',
'^webpack/hot',
'^regenerator-runtime',
'^@swc/helpers/(.*)',
'^universal-env',
'^@uni/env',
];
beforeAll(() => {
const spy = vi.spyOn(process, 'cwd');
spy.mockReturnValue(path.join(__dirname, '../../../examples/with-jest'));
});
it('get default config with object', async () => {
const jestConfigFn = defineJestConfig({});
const jestConfig = await jestConfigFn();
expect(Object.keys(jestConfig)).toStrictEqual(['moduleNameMapper']);
expect(Object.keys(jestConfig.moduleNameMapper as Record<string, string>)).toStrictEqual(builtInAlias);
});
it('get default config with function', async () => {
const jestConfigFn = defineJestConfig(async () => { return {}; });
const jestConfig = await jestConfigFn();
expect(Object.keys(jestConfig)).toStrictEqual(['moduleNameMapper']);
expect(Object.keys(jestConfig.moduleNameMapper as Record<string, string>)).toStrictEqual(builtInAlias);
});
it('get config with custom object config', async () => {
const jestConfigFn = defineJestConfig({ testTimeout: 12000 });
const jestConfig = await jestConfigFn();
expect(Object.keys(jestConfig)).toStrictEqual(['moduleNameMapper', 'testTimeout']);
});
it('get config with custom function config', async () => {
const jestConfigFn = defineJestConfig(async () => { return { testTimeout: 12000 }; });
const jestConfig = await jestConfigFn();
expect(Object.keys(jestConfig)).toStrictEqual(['moduleNameMapper', 'testTimeout']);
});
});
|
9,320 | 0 | petrpan-code/alibaba/ice/packages/ice | petrpan-code/alibaba/ice/packages/ice/tests/defineVitestConfig.test.ts | import * as path from 'path';
import { fileURLToPath } from 'url';
import { expect, it, describe, vi, beforeAll } from 'vitest';
import { defineVitestConfig } from '../src/test';
const __dirname = fileURLToPath(path.dirname(import.meta.url));
describe('defineVitestConfig', () => {
const builtInAlias = [
'ice',
'ice/types',
'@',
'webpack/hot',
'regenerator-runtime',
'@swc/helpers',
'universal-env',
'@uni/env',
];
beforeAll(() => {
const spy = vi.spyOn(process, 'cwd');
spy.mockReturnValue(path.join(__dirname, '../../../examples/with-vitest'));
});
it('get default config with object', async () => {
const vitestConfigFn = defineVitestConfig({});
const vitestConfig = await vitestConfigFn({ command: 'serve', mode: 'test' });
expect(Object.keys(vitestConfig.resolve as Record<string, string>)).toStrictEqual(['alias']);
expect(Object.keys(vitestConfig.resolve?.alias as Record<string, string>)).toStrictEqual(builtInAlias);
});
it('get default config with function', async () => {
const vitestConfigFn = defineVitestConfig(() => ({}));
const vitestConfig = await vitestConfigFn({ command: 'serve', mode: 'test' });
expect(Object.keys(vitestConfig.resolve as Record<string, string>)).toStrictEqual(['alias']);
expect(Object.keys(vitestConfig.resolve?.alias as Record<string, string>)).toStrictEqual(builtInAlias);
});
it('get config with custom object config', async () => {
const vitestConfigFn = defineVitestConfig({ test: { testTimeout: 12000 } });
const vitestConfig = await vitestConfigFn({ command: 'serve', mode: 'test' });
expect(Object.keys(vitestConfig.resolve as Record<string, string>)).toStrictEqual(['alias']);
expect(Object.keys(vitestConfig.test as Record<string, string>)).toStrictEqual(['testTimeout']);
});
it('get config with custom function config', async () => {
const vitestConfigFn = defineVitestConfig(async () => ({ test: { testTimeout: 12000 } }));
const vitestConfig = await vitestConfigFn({ command: 'serve', mode: 'test' });
expect(Object.keys(vitestConfig.resolve as Record<string, string>)).toStrictEqual(['alias']);
expect(Object.keys(vitestConfig.test as Record<string, string>)).toStrictEqual(['testTimeout']);
});
});
|
9,321 | 0 | petrpan-code/alibaba/ice/packages/ice | petrpan-code/alibaba/ice/packages/ice/tests/formatWebpackMessages.test.ts | import { expect, it, describe } from 'vitest';
import formatWebpackMessages from '../src/utils/formatWebpackMessages';
describe('webpack message formatting', () => {
it('format syntax error', () => {
const result = formatWebpackMessages({
errors: [{ message: 'Syntax error: Unterminated JSX contents (8:13)' }, { message: 'Module error' }],
warnings: [],
});
expect(result.errors.length).toBe(1);
});
it('formats aliased unknown export 1', () => {
const result = formatWebpackMessages({
errors: [{ message: 'export \'bar\' (imported as \'bar2\') was not found in \'./AppUnknownExport\'' }],
warnings: [],
});
expect(result.errors[0]).toBe('Attempted import error: \'bar\' is not exported from \'./AppUnknownExport\' (imported as \'bar2\').');
});
it('formats cannot find module sass', () => {
const result = formatWebpackMessages({
errors: [{ message: '\nCannot find module.import sass from \'sass\'' }],
warnings: [],
});
expect(result.errors[0]).toBe('To import Sass files, you first need to install sass.\nRun `npm install sass` or `yarn add sass` inside your workspace.');
});
it('formats module no found', () => {
const result = formatWebpackMessages({
errors: [{ message: '\nModule not found: Cannot find file: \'./ThisFileSouldNotExist\' in \'./src\'' }],
warnings: [],
});
expect(result.errors[0]).toBe('Cannot find file: \'./ThisFileSouldNotExist\' in \'./src\'');
});
it('remove leading newline', () => {
const result = formatWebpackMessages({
errors: [{ message: 'line1\n\n\n\nline3' }],
warnings: [],
});
expect(result.errors[0]).toBe('line1\n\nline3');
});
it('nested message', () => {
const result = formatWebpackMessages({
// @ts-ignore
errors: [[{ message: 'line1' }, { message: 'line2\nline3' }]],
warnings: [],
});
expect(result.errors[0]).toBe('line2\nline3');
});
it('string message', () => {
const result = formatWebpackMessages({
// @ts-ignore
errors: ['line2\nline3'],
warnings: [],
});
expect(result.errors[0]).toBe('line2\nline3');
});
it('eslint error', () => {
const result = formatWebpackMessages({
errors: [{ message: 'Line 4:13: Parsing error: \'b\' is not defined no-undef' }],
warnings: [],
});
expect(result.errors[0]).toBe('Syntax error: \'b\' is not defined no-undef (4:13)');
});
});
|
9,322 | 0 | petrpan-code/alibaba/ice/packages/ice | petrpan-code/alibaba/ice/packages/ice/tests/generator.test.ts | /**
* @vitest-environment jsdom
*/
import { expect, it, describe } from 'vitest';
import { generateDeclaration, checkExportData, removeDeclarations } from '../src/service/runtimeGenerator';
import { DeclarationType } from '../src/types/generator';
describe('generateDeclaration', () => {
it('basic usage', () => {
const { importStr, exportStr } = generateDeclaration([{
source: 'react-router',
specifier: 'Router',
type: false,
declarationType: DeclarationType.NORMAL,
}]);
expect(importStr).toBe('import Router from \'react-router\';');
expect(exportStr).toBe('Router,');
});
it('type export', () => {
const { importStr, exportStr } = generateDeclaration([{
source: 'react-router',
specifier: 'Router',
type: true,
declarationType: DeclarationType.NORMAL,
}]);
expect(importStr).toBe('import type Router from \'react-router\';');
expect(exportStr).toBe('Router;');
});
it('named exports', () => {
const { importStr, exportStr } = generateDeclaration([{
source: 'react-router',
specifier: ['Switch', 'Route'],
declarationType: DeclarationType.NORMAL,
}]);
expect(importStr).toBe('import { Switch, Route } from \'react-router\';');
expect(exportStr).toBe(['Switch,', 'Route,'].join('\n '));
});
it('aliased exports', () => {
const { importStr, exportStr } = generateDeclaration([{
source: 'react-helmet',
specifier: ['Helmet'],
alias: {
Helmet: 'Head',
},
declarationType: DeclarationType.NORMAL,
}]);
expect(importStr).toBe('import { Helmet as Head } from \'react-helmet\';');
expect(exportStr).toBe('Head,');
});
});
const defaultExportData = [{
source: 'react-router',
specifier: ['Switch', 'Route'],
declarationType: DeclarationType.NORMAL,
}, {
source: 'react-helmet',
specifier: 'Helmet',
declarationType: DeclarationType.NORMAL,
}];
describe('checkExportData', () => {
it('basic usage', () => {
checkExportData(defaultExportData, { source: 'react-dom', specifier: 'react-dom' }, 'test-api');
});
it('duplicate named export', () => {
expect(() => checkExportData(defaultExportData, defaultExportData[0], 'test-api')).toThrow();
});
it('duplicate exports', () => {
expect(() => checkExportData(defaultExportData, defaultExportData, 'test-api')).toThrow();
});
it('duplicate default export', () => {
expect(() => checkExportData(defaultExportData, { source: 'react-dom', specifier: 'Switch' }, 'test-api')).toThrow();
});
});
describe('removeDeclarations', () => {
it('basic usage', () => {
const removed = removeDeclarations(defaultExportData, 'react-router');
expect(removed.length).toBe(1);
expect(removed[0].source).toBe('react-helmet');
});
it('fail to remove', () => {
const removed = removeDeclarations(defaultExportData, ['react-dom']);
expect(removed.length).toBe(2);
});
it('remove exports', () => {
const removed = removeDeclarations(defaultExportData, ['react-router', 'react-helmet']);
expect(removed.length).toBe(0);
});
});
|
9,323 | 0 | petrpan-code/alibaba/ice/packages/ice | petrpan-code/alibaba/ice/packages/ice/tests/getRoutePaths.test.ts | import { expect, it, describe } from 'vitest';
import getRoutePaths from '../src/utils/getRoutePaths.js';
describe('getRoutePaths', () => {
it('index route with layout', () => {
const routeManifest = [
{
children: [
{},
],
},
];
// @ts-ignore for mock routeManifest.
const routePaths = getRoutePaths(routeManifest);
expect(routePaths).toEqual(['/']);
});
it('nested level 1', () => {
const routeManifest = [
{
children: [
{
path: 'a',
},
{
path: 'b',
},
],
},
];
// @ts-ignore for mock routeManifest.
const routePaths = getRoutePaths(routeManifest);
expect(routePaths).toEqual(['/a', '/b']);
});
it('nested level 2', () => {
const routeManifest = [
{
children: [
{
path: 'a',
children: [
{
path: 'a1',
},
{
path: 'a2',
},
],
},
{
path: 'b',
},
],
},
];
// @ts-ignore for mock routeManifest.
const routePaths = getRoutePaths(routeManifest, '/');
expect(routePaths).toEqual(['/a/a1', '/a/a2', '/b']);
});
it('nested level 3', () => {
const routeManifest = [
{
children: [
{
path: 'a',
children: [
{
path: 'a1',
children: [
{
path: 'a11',
},
],
},
],
},
{
path: 'b',
},
],
},
];
// @ts-ignore for mock routeManifest.
const routePaths = getRoutePaths(routeManifest);
expect(routePaths).toEqual(['/a/a1/a11', '/b']);
});
});
|
9,324 | 0 | petrpan-code/alibaba/ice/packages/ice | petrpan-code/alibaba/ice/packages/ice/tests/ignore.test.ts | import * as path from 'path';
import { fileURLToPath } from 'url';
import { afterAll, expect, it, describe } from 'vitest';
import fse from 'fs-extra';
import esbuild from 'esbuild';
import ignorePlugin from '../src/esbuild/ignore';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const rootDir = path.join(__dirname, './fixtures/ignore');
const cacheDir = path.join(rootDir, '.cache');
const appEntry = path.join(__dirname, './fixtures/ignore/app.ts');
const outfile = path.join(rootDir, 'build/index.js');
const buildOptions = {
bundle: true,
entryPoints: [appEntry],
outfile,
};
describe('esbuild ignore plugin', () => {
it('ignore with resourceRegExp', async () => {
await esbuild.build({
...buildOptions,
plugins: [
ignorePlugin([{
resourceRegExp: /ignored/,
}]),
],
});
const buildContent = await fse.readFile(outfile);
expect(buildContent.includes('ignored')).toBeFalsy();
expect(buildContent.includes('page')).toBeTruthy();
});
it('ignore with resourceRegExp', async () => {
await esbuild.build({
...buildOptions,
plugins: [
ignorePlugin([{
resourceRegExp: /.*/,
contextRegExp: /dir/,
}]),
],
});
const buildContent = await fse.readFile(outfile);
expect(buildContent.includes('ignored')).toBeTruthy();
expect(buildContent.includes('page')).toBeTruthy();
expect(buildContent.includes('content')).toBeFalsy();
});
it('ignore with resourceRegExp', async () => {
await esbuild.build({
...buildOptions,
plugins: [
// @ts-ignore error options
ignorePlugin({}),
],
});
const buildContent = await fse.readFile(outfile);
expect(buildContent.includes('ignored')).toBeTruthy();
expect(buildContent.includes('page')).toBeTruthy();
expect(buildContent.includes('content')).toBeTruthy();
});
afterAll(async () => {
await fse.remove(cacheDir);
});
});
|
9,325 | 0 | petrpan-code/alibaba/ice/packages/ice | petrpan-code/alibaba/ice/packages/ice/tests/nodeRunner.test.ts | import * as path from 'path';
import { fileURLToPath } from 'url';
import fs from 'fs';
import { expect, it, describe } from 'vitest';
import Runner from '../src/service/Runner';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
describe('node runner', () => {
const basicResolve = async (id, importee) => {
return id.startsWith('./') ? path.resolve(path.dirname(importee!), id) : id;
};
const basicLoad = async ({ path: id }) => {
if (id.endsWith('.js')) {
const code = fs.readFileSync(id, 'utf-8');
return {
code,
};
} else {
return {
externalize: id,
};
}
};
it('basic', async () => {
const rootDir = path.join(__dirname, './fixtures/nodeRunner/basic/');
const nodeRunner = new Runner({
rootDir,
resolveId: basicResolve,
load: basicLoad,
});
const result = await nodeRunner.run('entry.js');
expect(result.default).toBe(1);
});
it('cjs', async () => {
const rootDir = path.join(__dirname, './fixtures/nodeRunner/cjs/');
const nodeRunner = new Runner({
rootDir,
resolveId: basicResolve,
load: basicLoad,
});
const result = await nodeRunner.run('entry.js');
expect(result.default).toBe(1);
expect(result.a).toBe(1);
});
it('circular', async () => {
const rootDir = path.join(__dirname, './fixtures/nodeRunner/circular/');
const nodeRunner = new Runner({
rootDir,
load: basicLoad,
});
const result = await nodeRunner.run('entry.js');
expect(result.default).toEqual({
a: 'A',
b: 'Btest',
});
});
it('export all', async () => {
const rootDir = path.join(__dirname, './fixtures/nodeRunner/export-all/');
const nodeRunner = new Runner({
rootDir,
resolveId: basicResolve,
load: basicLoad,
});
const result = await nodeRunner.run('entry.js');
expect(result).toEqual({
a: 1,
b: 2,
});
});
it('externalize', async () => {
const rootDir = path.join(__dirname, './fixtures/nodeRunner/externalize/');
const nodeRunner = new Runner({
rootDir,
resolveId: basicResolve,
load: basicLoad,
});
const result = await nodeRunner.run('entry.js');
expect(typeof result.log).toBe('function');
expect(typeof result.default).toBe('object');
});
}); |
9,326 | 0 | petrpan-code/alibaba/ice/packages/ice | petrpan-code/alibaba/ice/packages/ice/tests/openBrowser.test.ts | import { expect, it, describe } from 'vitest';
import openBrowser from '../src/utils/openBrowser';
describe('openBrowser in node', () => {
it('open localhost', () => {
process.env.BROWSER = 'none';
const result = openBrowser('http://localhost/');
expect(result).toBe(false);
});
// TODO simulate open browser in node
}); |
9,327 | 0 | petrpan-code/alibaba/ice/packages/ice | petrpan-code/alibaba/ice/packages/ice/tests/preAnalyze.test.ts | import * as path from 'path';
import { fileURLToPath } from 'url';
import { expect, it, describe } from 'vitest';
import { analyzeImports, getImportPath, resolveId, type Alias } from '../src/service/analyze';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
describe('resolveId', () => {
it('alias: { ice: \'/.ice/runApp\'}; id: ice', () => {
const alias = { ice: '/.ice/runApp' };
const id = resolveId('ice', alias);
expect(id).toBe('/.ice/runApp');
});
it('alias: { ice: \'/.ice/runApp\'}; id: ice/test', () => {
const alias = { ice: '/.ice/runApp' };
const id = resolveId('ice/test', alias);
expect(id).toBe('/.ice/runApp/test');
});
it('alias: { ice$: \'/.ice/runApp\'}; id: ice/test', () => {
const alias = { ice$: '/.ice/runApp' };
const id = resolveId('ice/test', alias);
expect(id).toBe('ice/test');
});
it('alias: { ice: false}; id: false', () => {
const alias = { ice: false } as Alias;
const id = resolveId('ice', alias);
expect(id).toBe(false);
});
it('alias: { foundnamejs: \'/user/folder\'}; id: foundnamejs', () => {
const alias = { foundnamejs: '/user/folder' };
const id = resolveId('foundnamejs', alias);
expect(id).toBe('/user/folder');
});
it('alias with relative path', () => {
const alias = { ice: 'rax' } as Alias;
const id = resolveId('ice', alias);
expect(id).toBe('rax');
});
});
describe('getImportPath', () => {
it('import from relative path', () => {
const filePath = getImportPath('./page.js', '/rootDir/test.ts', {});
// Compatible with test case in win32.
expect(filePath.replace(/^[A-Za-z]:/, '')).toBe('/rootDir/page.js');
});
it('import from alias', () => {
const filePath = getImportPath('ice', '/rootDir/test.ts', { ice: '/rootDir/component.tsx' });
expect(filePath).toBe('/rootDir/component.tsx');
});
it('import node_module dependency', () => {
const filePath = getImportPath('ice', '/rootDir/test.ts', {});
expect(filePath).toBe('');
});
});
describe('analyzeImports', () => {
it('basic usage', async () => {
const entryFile = path.join(__dirname, './fixtures/preAnalyze/app.ts');
const analyzeSet = await analyzeImports([entryFile], {
analyzeRelativeImport: true,
alias: {
'@': path.join(__dirname, './fixtures/preAnalyze'),
},
});
expect([...(analyzeSet || [])]).toStrictEqual(['runApp', 'request', 'store']);
});
}); |
9,328 | 0 | petrpan-code/alibaba/ice/packages/ice | petrpan-code/alibaba/ice/packages/ice/tests/preBundleCJSDeps.test.ts | import * as path from 'path';
import { fileURLToPath } from 'url';
import { afterAll, expect, it } from 'vitest';
import fse from 'fs-extra';
import preBundleDeps from '../src/service/preBundleDeps';
import { scanImports } from '../src/service/analyze';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const alias = { '@': path.join(__dirname, './fixtures/scan') };
const rootDir = path.join(__dirname, './fixtures/scan');
const cacheDir = path.join(rootDir, '.cache');
it('prebundle cjs deps', async () => {
const deps = await scanImports([path.join(__dirname, './fixtures/scan/app.ts')], { alias, rootDir });
await preBundleDeps(deps, {
cacheDir,
alias,
rootDir,
taskConfig: { mode: 'production' },
});
expect(fse.pathExistsSync(path.join(cacheDir, 'deps', 'react.mjs'))).toBeTruthy();
expect(fse.pathExistsSync(path.join(cacheDir, 'deps', '@ice_runtime_client.mjs'))).toBeTruthy();
expect(fse.pathExistsSync(path.join(cacheDir, 'deps', '@ice_runtime.mjs'))).toBeTruthy();
});
afterAll(async () => {
await fse.remove(cacheDir);
});
|
9,329 | 0 | petrpan-code/alibaba/ice/packages/ice | petrpan-code/alibaba/ice/packages/ice/tests/scan.test.ts | import * as path from 'path';
import { fileURLToPath } from 'url';
import { expect, it, describe } from 'vitest';
import { scanImports } from '../src/service/analyze';
import formatPath from '../src/utils/formatPath';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
describe('scan import', () => {
const alias = { '@': path.join(__dirname, './fixtures/scan') };
const rootDir = path.join(__dirname, './fixtures/scan');
it('basic scan', async () => {
const deps = await scanImports([path.join(__dirname, './fixtures/scan/app.ts')], { alias, rootDir });
expect(deps['@ice/runtime'].name).toEqual('@ice/runtime');
expect(/(@ice\/)?runtime\/package\.json/.test(formatPath(deps['@ice/runtime'].pkgPath!))).toBeTruthy();
expect(deps['@ice/runtime/client'].name).toEqual('@ice/runtime/client');
expect(/(@ice\/)?runtime\/package\.json/.test(formatPath(deps['@ice/runtime/client'].pkgPath!))).toBeTruthy();
expect(deps.react.name).toEqual('react');
expect(/react\/package\.json/.test(formatPath(deps['react'].pkgPath!))).toBeTruthy();
});
it('scan with exclude', async () => {
const deps = await scanImports([path.join(__dirname, './fixtures/scan/app.ts')], { alias, rootDir, exclude: ['@ice/runtime'] });
expect(deps.react.name).toEqual('react');
expect(/react\/package\.json/.test(formatPath(deps['react'].pkgPath!))).toBeTruthy();
expect(deps['@ice/runtime']).toBeUndefined();
});
it('scan with depImports', async () => {
const deps = await scanImports(
[path.join(__dirname, './fixtures/scan/app.ts')],
{ alias, rootDir, depImports: { '@ice/runtime': { name: '@ice/runtime' }, react: { name: 'react' } } },
);
expect(deps['@ice/runtime'].name).toEqual('@ice/runtime');
expect(deps['@ice/runtime'].pkgPath).toBeUndefined();
expect(deps.react.name).toEqual('react');
expect(deps.react.pkgPath).toBeUndefined();
});
});
|
9,330 | 0 | petrpan-code/alibaba/ice/packages/ice | petrpan-code/alibaba/ice/packages/ice/tests/transformImport.test.ts | import * as path from 'path';
import { fileURLToPath } from 'url';
import { afterAll, expect, it } from 'vitest';
import fse from 'fs-extra';
import esbuild from 'esbuild';
import { createUnplugin } from 'unplugin';
import preBundleDeps from '../src/service/preBundleDeps';
import { scanImports } from '../src/service/analyze';
import transformImport from '../src/esbuild/transformImport';
import externalPlugin from '../src/esbuild/external';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const alias = { '@': path.join(__dirname, './fixtures/scan') };
const rootDir = path.join(__dirname, './fixtures/scan');
const cacheDir = path.join(rootDir, '.cache');
const appEntry = path.join(__dirname, './fixtures/scan/import.js');
const outdir = path.join(rootDir, 'build');
it('transform module import', async () => {
const deps = await scanImports([appEntry], { alias, rootDir });
const { metadata } = await preBundleDeps(deps, {
rootDir,
cacheDir,
alias,
taskConfig: { mode: 'production' },
});
const transformImportPlugin = createUnplugin(() => transformImport(metadata!, path.join(outdir, 'server'))).esbuild;
await esbuild.build({
alias,
bundle: true,
entryPoints: [appEntry],
outdir,
plugins: [
externalPlugin({ format: 'esm', externalDependencies: false }),
transformImportPlugin(),
],
});
const buildContent = await fse.readFile(path.join(outdir, 'import.js'), 'utf-8');
expect(buildContent.includes('../../.cache/deps/@ice_runtime_client.mjs')).toBeTruthy();
expect(buildContent.includes('../../.cache/deps/@ice_runtime.mjs')).toBeTruthy();
});
afterAll(async () => {
await fse.remove(cacheDir);
});
|
9,362 | 0 | petrpan-code/alibaba/ice/packages/jsx-runtime | petrpan-code/alibaba/ice/packages/jsx-runtime/tests/hijackElememt.test.ts | import { expect, it, describe } from 'vitest';
import { hijackElementProps } from '../src/';
describe('hijack element', () => {
it('hijackElementProps basic', () => {
const props = hijackElementProps({ data: '', number: 1, fontSize: '12rpx' });
expect(props).toStrictEqual({
data: '', number: 1, fontSize: '12rpx',
});
});
it('hijackElementProps style', () => {
const props = hijackElementProps({ style: { fontSize: 14, height: '12px', with: '12rpx' } });
expect(props).toStrictEqual({
style: {
fontSize: 14,
height: '12px',
with: '1.6vw',
},
});
});
}); |
9,539 | 0 | petrpan-code/alibaba/ice/packages/plugin-jsx-plus | petrpan-code/alibaba/ice/packages/plugin-jsx-plus/tests/jsxplus.test.ts | import { expect, it, describe } from 'vitest';
import { default as jsxPlus, idFilter } from '../src';
describe('JSX Plus Plugin', () => {
describe('Id filter', () => {
it('default', () => {
expect(idFilter({}, '/bar/a.tsx')).toBeFalsy();
});
it('include', () => {
const options = {
include: [/bar/, 'foo'],
extensions: ['.jsx', '.tsx'],
};
expect(idFilter(options, '/bar/a.tsx')).toBeTruthy();
expect(idFilter(options, '/foo/a.tsx')).toBeTruthy();
});
it('exclude', () => {
expect(idFilter({
exclude: ['foo'],
include: [/bar/],
extensions: ['.jsx', '.tsx'],
}, '/foo/bar/a.tsx')).toBeFalsy();
expect(idFilter({
exclude: [/foo/],
include: [/bar/],
extensions: ['.jsx', '.tsx'],
}, '/foo/bar/a.tsx')).toBeFalsy();
});
it('extensions', () => {
const options = {
include: [/bar/],
extensions: ['.jsx', '.tsx', '.custom.ext'],
};
expect(idFilter(options, '/foo/bar/a.tsx.custom.ext')).toBeTruthy();
});
});
describe('Plugin', () => {
it('default', () => {
const plugin = jsxPlus({
include: ['foo'],
});
// @ts-ignore
expect(plugin.name).toBe('@ice/plugin-jsx-plus');
const fakeConfig = {};
function onGetConfig(fn) {
fn(fakeConfig);
}
const context = {
rootDir: '/foo/bar',
};
// @ts-ignore
plugin.setup({ onGetConfig, context });
expect(fakeConfig['alias']['babel-runtime-jsx-plus']).toBeDefined();
expect(Array.isArray(fakeConfig['transforms'])).toBeTruthy();
expect(fakeConfig['transforms'].length).toBe(1);
});
it('transformer', () => {
const plugin = jsxPlus({
include: ['foo'],
});
const fakeConfig = {};
function onGetConfig(fn) {
fn(fakeConfig);
}
const context = {
rootDir: '/foo/bar',
};
// @ts-ignore
plugin.setup({ onGetConfig, context });
const transformer = fakeConfig['transforms'][0];
const ret = transformer('<div x-if={false} />', '/foo/bar/a.tsx');
expect(ret.code).toBe(`import { createCondition as __create_condition__ } from "babel-runtime-jsx-plus";
__create_condition__([[() => false, () => <div />]]);`);
});
it('transformer w/ parent element is a <></>', () => {
const plugin = jsxPlus({
include: ['foo'],
});
const fakeConfig = {};
function onGetConfig(fn) {
fn(fakeConfig);
}
const context = {
rootDir: '/foo/bar',
};
// @ts-ignore
plugin.setup({ onGetConfig, context });
const transformer = fakeConfig['transforms'][0];
const ret = transformer('<><div x-if={true} /></>', '/foo/bar/a.tsx');
expect(ret.code).toBe(`import { createCondition as __create_condition__ } from "babel-runtime-jsx-plus";
import { Fragment } from "react";
<>{__create_condition__([[() => true, () => <div />]])}</>;`);
});
});
}); |
9,593 | 0 | petrpan-code/alibaba/ice/packages/plugin-pha | petrpan-code/alibaba/ice/packages/plugin-pha/tests/manifestHelper.test.ts | import * as path from 'path';
import { fileURLToPath } from 'url';
import { expect, it, describe } from 'vitest';
import { transformManifestKeys, parseManifest, getAppWorkerUrl, rewriteAppWorker, getMultipleManifest } from '../src/manifestHelpers';
import * as mockServer from './mockServer.mjs';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
describe('get app work url', () => {
it('app worker config as remote url', () => {
const manifest = {
appWorker: {
url: 'http://remote/app-worker.js',
},
};
const appWorkerPath = getAppWorkerUrl(manifest, __dirname);
expect(appWorkerPath).toBeUndefined();
});
it('app worker config which do not exist', () => {
const manifest = {
appWorker: {
url: 'app-worker.js',
},
};
const appWorkerPath = getAppWorkerUrl(manifest, __dirname);
expect(appWorkerPath).toBeUndefined();
});
it('app worker config which exists', () => {
const manifest = {
appWorker: {
url: 'pha-work.js',
},
};
const appWorkerPath = getAppWorkerUrl(manifest, __dirname);
expect(appWorkerPath).toBe(path.join(__dirname, 'pha-work.js'));
});
it('found default app worker', () => {
const manifest = {};
const appWorkerPath = getAppWorkerUrl(manifest, __dirname);
expect(appWorkerPath).toBe(path.join(__dirname, 'app-worker.ts'));
});
});
describe('rewrite app worker url', () => {
it('over write appWorker.url', () => {
expect(rewriteAppWorker({
appWorker: {
url: 'pha-worker.js',
source: 'test',
},
})).toMatchObject({
appWorker: {
url: 'app-worker.js',
source: 'test',
},
});
});
it('config appWorker', () => {
expect(rewriteAppWorker({})).toMatchObject({
appWorker: {
url: 'app-worker.js',
},
});
});
});
describe('transform config keys', () => {
it('should transform decamelize keys fields', () => {
const manifestJSON = transformManifestKeys(
{
offlineResources: ['//g.alicdn.com/.*'],
name: 'name',
pages: [
{
pageHeader: {
includedSafeArea: true,
},
downgradeUrl: 'http://www.taobao.com',
},
],
},
{ isRoot: true },
);
expect(manifestJSON.name).toStrictEqual('name');
expect(manifestJSON?.pages![0].downgrade_url).toStrictEqual('http://www.taobao.com');
expect(manifestJSON.offline_resources).toStrictEqual(['//g.alicdn.com/.*']);
expect(manifestJSON?.pages![0].tab_header).toStrictEqual({ included_safe_area: true });
});
it('should transform dataPrefetch to data_prefetch', () => {
const manifestJSON = transformManifestKeys(
{
dataPrefetch: [
{
api: '/a.com',
data: {
id: 123,
taskId: 233,
cId: {
dId: true,
},
},
header: {
taskId: 455,
},
extHeaders: {
id: 123,
test_id: 234,
},
dataType: 'json',
appKey: '12345',
LoginRequest: true,
},
],
},
{ isRoot: true },
);
expect(manifestJSON?.data_prefetch?.length).toBe(1);
expect(manifestJSON?.data_prefetch![0].data).toMatchObject({
id: 123,
taskId: 233,
cId: {
dId: true,
},
});
expect(manifestJSON?.data_prefetch![0].header).toMatchObject({
taskId: 455,
});
expect(manifestJSON?.data_prefetch![0].ext_headers).toMatchObject({ id: 123, test_id: 234 });
expect(manifestJSON?.data_prefetch![0].dataType).toBe('json');
expect(manifestJSON?.data_prefetch![0].appKey).toBe('12345');
expect(manifestJSON?.data_prefetch![0].LoginRequest).toBe(true);
expect(manifestJSON?.data_prefetch![0].prefetch_key).toBe('mtop');
});
it('should transform tabBar to tab_bar', () => {
const manifestJSON = transformManifestKeys(
{
tabBar: {
textColor: '',
selectedColor: '',
backgroundColor: '',
items: [
{
path: 'tab1',
name: '主会场',
icon: '',
activeIcon: '',
},
{
// transform text to name
text: 'text-name',
icon: '',
activeIcon: '',
},
],
},
},
{ isRoot: true },
);
expect(manifestJSON.tab_bar).toBeTruthy();
expect(manifestJSON?.tab_bar?.items![0]).toMatchObject({ path: 'tab1', name: '主会场', icon: '', active_icon: '' });
});
it('should transform pages keys', () => {
const manifestJSON = transformManifestKeys(
{
pages: [
{
path: '/',
name: 'home',
source: 'pages/Home/index',
dataPrefetch: [
{
url: '/a.com',
data: {
id: 123,
},
},
],
},
{
path: '/home1',
name: 'home1',
source: 'pages/Home1/index',
},
],
},
{ isRoot: true },
);
expect(manifestJSON?.pages?.length).toBe(2);
expect(manifestJSON?.pages![0].data_prefetch).toMatchObject([
{
url: '/a.com',
data: {
id: 123,
},
header: {},
prefetch_key: 'mtop',
},
]);
});
it('should not filter whitelist fields', () => {
const manifestJSON = transformManifestKeys(
{
a: 123,
},
{ isRoot: false },
);
expect(manifestJSON).toMatchObject({ a: 123 });
});
it('should transform enableExpiredManifest', () => {
const manifestJSON = transformManifestKeys(
{
enableExpiredManifest: true,
},
{ isRoot: false },
);
expect(manifestJSON).toMatchObject({ enable_expired_manifest: true });
});
it('should filter unknown fields in root', () => {
const manifestJSON = transformManifestKeys(
{
a: 123,
},
{ isRoot: true },
);
expect(manifestJSON).toMatchObject({});
});
it('should not transform requestHeaders', () => {
const manifestJSON = transformManifestKeys(
{
requestHeaders: {
'U-Tag': '${storage.uTag}',
},
},
{ isRoot: false },
);
expect(manifestJSON).toMatchObject({ request_headers: { 'U-Tag': '${storage.uTag}' } });
});
});
describe('parse manifest', async () => {
const options = {
publicPath: 'https://cdn-path.com/',
urlPrefix: 'https://url-prefix.com/',
routesConfig: (await import(path.join(__dirname, './mockConfig.mjs')))?.default,
excuteServerEntry: async () => mockServer,
routeManifest: path.join(__dirname, './route-manifest.json'),
};
it('should add urlPrefix to manifest', async () => {
const phaManifest = {
appWorker: {
url: 'pha-worker.js',
},
routes: [
'home',
'about',
'app/nest',
],
};
const manifest = await parseManifest(phaManifest, options);
expect(manifest?.pages![0].path).toBe('https://url-prefix.com/home');
expect(manifest?.pages![0].key).toBe('home');
expect(manifest?.pages![0].title).toBe('title-home');
expect(manifest?.pages![0].priority).toBe('low');
expect(manifest?.pages![1].path).toBe('https://url-prefix.com/about?c=123');
expect(manifest?.pages![2]?.frames![1].path).toBe('https://m.taobao.com');
expect(manifest?.app_worker?.url).toBe('https://cdn-path.com/pha-worker.js');
});
it('multiple should work with frames', async () => {
const phaManifest = {
routes: [
'home',
'about',
{
defaultFrameIndex: 0,
frames: ['home', 'about'],
},
],
};
const manifest = await parseManifest(phaManifest, options);
const remultipleManifests = await getMultipleManifest(manifest);
expect(remultipleManifests['home']?.pages![0]?.frames?.length).toBe(2);
});
it('should work with enable pull refresh', async () => {
const phaManifest = {
appWorker: {
url: 'pha-worker.js',
},
pullRefresh: {
reload: false,
},
routes: [
{
path: '/',
name: 'home',
},
{
path: '/about',
name: 'about',
},
{
path: '/',
name: 'frames',
frames: [
{
name: 'frame1',
url: 'https://m.taobao.com',
},
{
name: 'frame2',
url: 'https://m.taobao.com',
},
],
},
],
};
const manifest = await parseManifest(phaManifest, options);
expect(manifest?.pages![0].enable_pull_refresh).toBe(true);
expect(manifest?.pages![1].enable_pull_refresh).toBe(true);
expect(manifest?.pages![2].enable_pull_refresh).toBe(true);
});
it('should work with enable pull refresh', async () => {
const phaManifest = {
appWorker: {
url: 'pha-worker.js',
},
pullRefresh: {
reload: true,
},
routes: [
{
path: '/',
name: 'home',
pullRefresh: {
reload: true,
},
},
{
path: '/about',
name: 'about',
},
{
path: '/',
name: 'frames',
frames: [
{
name: 'frame1',
url: 'https://m.taobao.com',
pullRefresh: {
reload: true,
},
},
{
name: 'frame2',
url: 'https://m.taobao.com',
pullRefresh: {
reload: true,
},
},
],
},
],
};
const manifest = await parseManifest(phaManifest, options);
expect(manifest?.pages![0].pull_refresh).toBe(true);
expect(manifest?.pages![1].pull_refresh).toBe(true);
expect(manifest?.pages![2].frames![0].pull_refresh).toBe(true);
expect(manifest?.pages![2].frames![1].pull_refresh).toBe(true);
});
it('pull refresh of manifest should be default value of page', async () => {
const phaManifest = {
appWorker: {
url: 'pha-worker.js',
},
pullRefresh: {
reload: true,
},
routes: [
{
path: '/',
name: 'home',
},
{
path: '/about',
name: 'about',
},
],
};
const manifest = await parseManifest(phaManifest, options);
expect(manifest?.pages![0].pull_refresh).toBe(true);
expect(manifest?.pages![1].pull_refresh).toBe(true);
});
it('enable pull refresh of manifest should be default value of page', async () => {
const phaManifest = {
appWorker: {
url: 'pha-worker.js',
},
pullRefresh: true,
routes: [
{
path: '/',
name: 'home',
},
{
path: '/about',
name: 'about',
},
],
};
const manifest = await parseManifest(phaManifest, options);
expect(manifest?.pages![0].enable_pull_refresh).toBe(true);
expect(manifest?.pages![1].enable_pull_refresh).toBe(true);
});
it('enable pull refresh of page should cover value of page', async () => {
const phaManifest = {
appWorker: {
url: 'pha-worker.js',
},
pullRefresh: {
reload: true,
},
routes: [
{
path: '/',
name: 'home',
pullRefresh: {
reload: true,
},
},
{
path: '/about',
name: 'about',
},
],
};
const manifest = await parseManifest(phaManifest, options);
expect(manifest?.pages![0].pull_refresh).toBe(true);
expect(manifest?.pages![1].pull_refresh).toBe(true);
});
it('should work with enable pull refresh', async () => {
const phaManifest = {
appWorker: {
url: 'pha-worker.js',
},
routes: [
{
path: '/',
name: 'home',
pullRefresh: true,
},
],
};
const manifest = await parseManifest(phaManifest, options);
expect(manifest?.pages![0].enable_pull_refresh).toBe(true);
});
it('should set document to manifest', async () => {
const phaManifest = {
routes: [
'home',
'about',
'app/nest',
],
};
const manifest = await parseManifest(phaManifest, {
...options,
template: true,
});
expect(manifest?.pages![0].document).toBe('<html><body>/home-document</body></html>');
expect(manifest?.pages![1].document).toBe('<html><body>/about-document</body></html>');
expect(manifest?.pages![2]?.frames![0].document).toBe('<html><body>/home-document</body></html>');
});
it('should not support template', async () => {
const phaManifest = {
routes: [
'home',
'about',
'app/nest',
'404',
],
};
const manifest = await parseManifest(phaManifest, {
...options,
template: false,
});
expect(manifest.pages![0].script).toBeUndefined();
expect(manifest.pages![0].stylesheet).toBeUndefined();
expect(manifest.pages![0].document).toBeUndefined();
});
it('should config url to path when user config page.url', async () => {
const phaManifest = {
routes: [
{
path: '/',
name: 'home',
url: 'https://m.taobao.com',
},
{
pageHeader: {
url: 'https://m.taobao.com',
source: 'pages/Header',
},
frames: [
{
path: '/frame1',
name: 'frame1',
url: 'https://m.taobao.com',
},
],
},
'about',
],
tabBar: {
custom: true,
items: ['home', 'frame1'],
url: 'https://m.taobao.com',
},
};
// @ts-ignore ignore type error with mix config key
const manifest = await parseManifest(phaManifest, options);
expect(manifest.pages![0].path).toBe('https://m.taobao.com');
// @ts-ignore
expect(manifest.pages![0].url).toBeUndefined();
expect(manifest.pages![0].script).toBeUndefined();
expect(manifest.pages![0].stylesheet).toBeUndefined();
expect(manifest.pages![1]?.tab_header?.url).toBe('https://m.taobao.com');
// @ts-ignore
expect(manifest.pages![1]?.tab_header?.source).toBeUndefined();
expect(manifest.pages![1]?.frames![0].path).toBe('https://m.taobao.com');
// @ts-ignore
expect(manifest.pages![1]?.frames![0].url).toBeUndefined();
expect(manifest.pages![1]?.frames![0].script).toBeUndefined();
expect(manifest.pages![1]?.frames![0].stylesheet).toBeUndefined();
expect(manifest?.tab_bar?.url).toBe('https://m.taobao.com');
// @ts-ignore
expect(manifest?.tab_bar?.source).toBeUndefined();
expect(manifest?.tab_bar?.items).toHaveLength(2);
expect(manifest.pages![2].path).toBe('https://url-prefix.com/about?c=123');
});
it('should not cover url by pageUrl', async () => {
const phaManifest = {
routes: [
{
pageHeader: {
source: 'pages/header',
},
frames: [
{
name: 'frame1',
url: 'https://m.taobao.com',
},
],
},
],
tabBar: {
custom: true,
source: 'pages/CustomTabBar',
items: ['home', 'frame1'],
},
};
const manifest = await parseManifest(phaManifest, {
...options,
template: true,
});
expect(manifest.pages![0]?.tab_header?.url).toBe('https://url-prefix.com/header');
expect(manifest.pages![0]?.tab_header?.html).toBe('<html><body>/header-document</body></html>');
expect(manifest?.tab_bar?.url).toBe('https://url-prefix.com/CustomTabBar');
});
it('should not set html to tabBar when template is false', async () => {
const phaManifest = {
routes: [
{
pageHeader: {
source: 'pages/header',
},
frames: [
{
name: 'frame1',
url: 'https://m.taobao.com',
},
],
},
],
tabBar: {
custom: true,
source: 'pages/CustomTabBar',
items: ['home', 'frame1'],
},
};
const manifest = await parseManifest(phaManifest, {
...options,
template: false,
});
expect(manifest.pages![0]?.tab_header?.html).toBeUndefined();
});
it('error source without pages', async () => {
const phaManifest = {
tabBar: {
source: 'components/CustomTabBar',
},
};
try {
await parseManifest(phaManifest, options);
expect(true).toBe(false);
} catch (err) {
expect(true).toBe(true);
}
});
it('url failed with new URL', async () => {
const phaManifest = {
tabBar: {
source: 'pages/tabBar',
},
};
const manifest = await parseManifest(phaManifest, {
...options,
urlPrefix: '{{xxx}}/',
});
expect(manifest.tab_bar?.url).toBe('{{xxx}}/tabBar');
expect(manifest.tab_bar?.name).toBe('{{xxx}}');
});
it('should not inject html when tabHeader & tabBar have url field', async () => {
const phaManifest = {
routes: [
{
pageHeader: {
source: 'pages/Header',
url: 'https://m.taobao.com',
},
},
],
tabBar: {
custom: true,
source: 'pages/CustomTabBar',
items: ['home', 'frame1'],
},
};
const manifest = await parseManifest(phaManifest, {
...options,
template: true,
});
expect(manifest.pages![0].tab_header?.url).toBe('https://m.taobao.com');
expect(manifest.pages![0].tab_header?.html).toBeUndefined();
expect(manifest.tab_bar?.url).toBe('https://url-prefix.com/CustomTabBar');
});
it('should work with static dataloader', async () => {
const phaManifest = {
title: 'test',
routes: [
{
pageHeader: {},
frames: [
'blog',
'home',
'about',
],
},
'home',
'about',
],
};
const staticDataloader = {
key: 'dataLoader222',
prefetch_type: 'mtop',
api: 'query222',
v: '0.0.1',
data: {
aaa: 111,
},
ext_headers: {},
};
const manifest = await parseManifest(phaManifest, {
...options,
dataloaderConfig: {
home: {
loader: [
() => {
return new Promise((resolve) => {
setTimeout(() => {
resolve({
name: 'About',
});
}, 1 * 100);
});
},
staticDataloader,
],
},
},
});
expect(manifest.pages![0].frames![1].data_prefetch?.length).toBe(1);
expect(manifest.pages![1].data_prefetch?.length).toBe(2);
expect(manifest.pages![2].data_prefetch).toBeUndefined();
});
it('prefetch of dataloader should not be decamelized', async () => {
const phaManifest = {
title: 'test',
routes: [
{
pageHeader: {},
frames: [
'blog',
'home',
'about',
],
},
'home',
'about',
],
};
const staticDataloader = {
key: 'dataLoader222',
prefetch_type: 'mtop',
api: 'query222',
v: '0.0.1',
data: {
aaa: 111,
aaB: 222,
},
ext_headers: {},
};
const manifest = await parseManifest(phaManifest, {
...options,
dataloaderConfig: {
home: {
loader: [
() => {
return new Promise((resolve) => {
setTimeout(() => {
resolve({
name: 'About',
});
}, 1 * 100);
});
},
staticDataloader,
],
},
},
});
expect(manifest.pages![1].data_prefetch![1]?.data.aaB).toBe(222);
});
});
describe('get multiple manifest', async () => {
const options = {
publicPath: 'https://cdn-path.com/',
urlPrefix: 'https://url-prefix.com/',
routesConfig: (await import(path.join(__dirname, './mockConfig.mjs')))?.default,
excuteServerEntry: async () => mockServer,
routeManifest: path.join(__dirname, './route-manifest.json'),
};
it('simple routes', async () => {
const phaManifest = {
routes: [
'home',
'about',
],
};
const manifest = await parseManifest(phaManifest, options);
const multipleManifest = getMultipleManifest(manifest);
expect(multipleManifest?.home?.pages?.length).toBe(1);
expect(multipleManifest?.home?.data_prefetch).toMatchObject([{ api: 'test/api' }]);
expect(multipleManifest?.about?.pages?.length).toBe(1);
});
it('routes with frame', async () => {
const phaManifest = {
routes: [
{
frames: [
'app/nest',
{
url: 'https://m.taobao.com',
},
],
},
'about',
],
};
const manifest = await parseManifest(phaManifest, options);
const multipleManifest = getMultipleManifest(manifest);
expect(multipleManifest?.['app/nest']?.pages?.length).toBe(1);
expect(multipleManifest?.['app/nest']?.pages![0].frames?.length).toBe(2);
expect(multipleManifest?.about?.pages?.length).toBe(1);
});
});
|
9,676 | 0 | petrpan-code/alibaba/ice/packages/rax-compat | petrpan-code/alibaba/ice/packages/rax-compat/tests/children.test.tsx | /**
* @vitest-environment jsdom
*/
import React from 'react';
import { expect, it, describe } from 'vitest';
import { render } from '@testing-library/react';
import Children from '../src/children';
const arrText = ['hello', 'rax'];
describe('children', () => {
it('should work with map', () => {
function Hello({ children }) {
return (<div data-testid="test">
{
Children.map(children, (child, i) => {
if (i === 0) {
return <span>{arrText[1]}</span>;
}
return child;
})
}
</div>);
}
const instance = (
<Hello>
<span>{arrText[0]}</span>
<span>{arrText[1]}</span>
</Hello>
);
const wrapper = render(instance);
const node = wrapper.queryByTestId('test');
expect(node.children.item(0).textContent).toBe(node.children.item(0).textContent);
expect(node.children.item(1).textContent).toBe(arrText[1]);
});
it('should work with forEach', () => {
function Hello({ children }) {
Children.forEach(children, (child, i) => {
expect(child.type).toBe('span');
expect(child.props.children).toBe(arrText[i]);
});
return children;
}
const instance = (
<Hello>
<span>{arrText[0]}</span>
<span>{arrText[1]}</span>
</Hello>
);
render(instance);
});
it('should work with count', () => {
function Hello({ children }) {
expect(Children.count(children)).toBe(arrText.length);
return children;
}
const instance = (
<Hello>
<span>{arrText[0]}</span>
<span>{arrText[1]}</span>
</Hello>
);
render(instance);
});
it('should work with only', () => {
let child = <span>{arrText[0]}</span>;
function Hello({ children }) {
expect(Children.only(children)).toBe(child);
return children;
}
const instance = (
<Hello>
{
child
}
</Hello>
);
render(instance);
});
it('should work with toArray', () => {
function Hello({ children }) {
expect(Children.toArray(children).length).toBe(arrText.length);
return children;
}
const instance = (
<Hello>
<span>{arrText[0]}</span>
<span>{arrText[1]}</span>
</Hello>
);
render(instance);
});
it('should escape keys', () => {
const zero = <div key="1" />;
const one = <div key="1=::=2" />;
const instance = (
<div>
{zero}
{one}
</div>
);
const mappedChildren = Children.map(
instance.props.children,
kid => kid,
);
expect(mappedChildren).toEqual([
<div key=".$1" />,
<div key=".$1=0=2=2=02" />,
]);
});
it('should combine keys when map returns an array', () => {
const instance = (
<div>
<div key="a" />
{false}
<div key="b" />
<p />
</div>
);
const mappedChildren = Children.map(
instance.props.children,
// Try a few things: keyed, unkeyed, hole, and a cloned element.
kid => [
<span key="x" />,
null,
<span key="y" />,
kid,
kid && React.cloneElement(kid, { key: 'z' }),
<hr />,
],
);
expect(mappedChildren.length).toBe(18);
// <div key="a">
expect(mappedChildren[0].type).toBe('span');
expect(mappedChildren[0].key).toBe('.$a/.$x');
expect(mappedChildren[1].type).toBe('span');
expect(mappedChildren[1].key).toBe('.$a/.$y');
expect(mappedChildren[2].type).toBe('div');
expect(mappedChildren[2].key).toBe('.$a/.$a');
expect(mappedChildren[3].type).toBe('div');
expect(mappedChildren[3].key).toBe('.$a/.$z');
expect(mappedChildren[4].type).toBe('hr');
expect(mappedChildren[4].key).toBe('.$a/.5');
// false
expect(mappedChildren[5].type).toBe('span');
expect(mappedChildren[5].key).toBe('.1/.$x');
expect(mappedChildren[6].type).toBe('span');
expect(mappedChildren[6].key).toBe('.1/.$y');
expect(mappedChildren[7].type).toBe('hr');
expect(mappedChildren[7].key).toBe('.1/.5');
// <div key="b">
expect(mappedChildren[8].type).toBe('span');
expect(mappedChildren[8].key).toBe('.$b/.$x');
expect(mappedChildren[9].type).toBe('span');
expect(mappedChildren[9].key).toBe('.$b/.$y');
expect(mappedChildren[10].type).toBe('div');
expect(mappedChildren[10].key).toBe('.$b/.$b');
expect(mappedChildren[11].type).toBe('div');
expect(mappedChildren[11].key).toBe('.$b/.$z');
expect(mappedChildren[12].type).toBe('hr');
expect(mappedChildren[12].key).toBe('.$b/.5');
// <p>
expect(mappedChildren[13].type).toBe('span');
expect(mappedChildren[13].key).toBe('.3/.$x');
expect(mappedChildren[14].type).toBe('span');
expect(mappedChildren[14].key).toBe('.3/.$y');
expect(mappedChildren[15].type).toBe('p');
expect(mappedChildren[15].key).toBe('.3/.3');
expect(mappedChildren[16].type).toBe('p');
expect(mappedChildren[16].key).toBe('.3/.$z');
expect(mappedChildren[17].type).toBe('hr');
expect(mappedChildren[17].key).toBe('.3/.5');
});
});
|
9,677 | 0 | petrpan-code/alibaba/ice/packages/rax-compat | petrpan-code/alibaba/ice/packages/rax-compat/tests/cloneElement.test.tsx | /**
* @vitest-environment jsdom
*/
import React from 'react';
import { expect, it, describe } from 'vitest';
import { render } from '@testing-library/react';
import { Component } from '../src/index';
import cloneElement from '../src/clone-element';
describe('cloneElement', () => {
it('basic', () => {
class TextComponent extends Component {
render() {
return <div data-testid="TextComponent" >render text</div>;
}
}
const wrapper = render(cloneElement(<TextComponent />));
const node = wrapper.queryByTestId('TextComponent');
expect(node.textContent).toBe('render text');
});
});
|
9,678 | 0 | petrpan-code/alibaba/ice/packages/rax-compat | petrpan-code/alibaba/ice/packages/rax-compat/tests/component.test.tsx | /**
* @vitest-environment jsdom
*/
import React from 'react';
import { expect, it, describe } from 'vitest';
import { render } from '@testing-library/react';
import { Component, PureComponent, memo } from '../src/index';
describe('component', () => {
it('Component should work', () => {
class MyComponent extends Component {
render() {
return <div data-testid="componentId" >my component</div>;
}
}
const wrapper = render(<MyComponent />);
const node = wrapper.queryByTestId('componentId');
expect(node.textContent).toBe('my component');
});
it('PureComponent should work', () => {
class MyComponent extends PureComponent {
render() {
return <div data-testid="pureComponentId" >my component</div>;
}
}
const wrapper = render(<MyComponent />);
const node = wrapper.queryByTestId('pureComponentId');
expect(node.textContent).toBe('my component');
});
it('memo should work', () => {
const MyComponent = memo((props: { text: string; id: string }) => {
return <div id={props.id}>{props.text}</div>;
});
const wrapper = render(<MyComponent id="" text="memo demo" />);
const res = wrapper.queryAllByText('memo demo');
expect(res.length).toBe(1);
});
});
|
9,679 | 0 | petrpan-code/alibaba/ice/packages/rax-compat | petrpan-code/alibaba/ice/packages/rax-compat/tests/createElement.test.tsx | /**
* @vitest-environment jsdom
*/
import { expect, it, describe, vi } from 'vitest';
import { render } from '@testing-library/react';
import { createElement } from '../src/index';
describe('createElement', () => {
it('basic', () => {
const str = 'hello world';
const wrapper = render(createElement(
'div',
null,
str,
));
expect(wrapper.container.childNodes[0].textContent).toBe(str);
});
it('should work with onAppear', () => {
let appearFun = vi.spyOn({
func: () => {
expect(appearFun).toHaveBeenCalled();
},
}, 'func');
const str = 'hello world';
render(createElement(
'div',
{
onAppear: appearFun,
},
str,
));
});
it('should work with onDisappear', () => {
const func = () => {
expect(disappearFun).toHaveBeenCalled();
};
let disappearFun = vi.spyOn({
func: func,
}, 'func');
const str = 'hello world';
render(createElement(
'div',
{
onDisappear: func,
},
str,
));
});
it('component should not work with onAppear', () => {
let appearFun = vi.spyOn({
func: () => {
expect(appearFun).toBeCalledTimes(0);
},
}, 'func');
const str = 'hello world';
const FunctionComponent = ({ onDisappear }) => {
expect(typeof onDisappear).toBe('function');
return createElement('div');
};
render(createElement(
FunctionComponent,
{
onDisappear: appearFun,
},
str,
));
});
it('rpx should transform to vw', () => {
const str = 'hello world';
const wrapper = render(createElement(
'div',
{
'data-testid': 'rpxTest',
style: {
width: '300rpx',
},
},
str,
));
const node = wrapper.queryByTestId('rpxTest');
expect(node.style.width).toBe('40vw');
});
it('should work with value', () => {
const str = 'hello world';
const wrapper = render(createElement(
'input',
{
'data-testid': 'valueTest',
value: str,
},
));
const node = wrapper.queryByTestId('valueTest') as HTMLInputElement;
expect(node.value).toBe(str);
});
it('input set empty string to maxlength not be 0', () => {
const str = 'hello world';
const wrapper = render(createElement(
'input',
{
'data-testid': 'maxlengthTest',
value: str,
maxlength: '',
},
));
const node = wrapper.queryByTestId('valueTest');
expect(node?.getAttribute('maxlength')).toBe(null);
});
});
|
9,680 | 0 | petrpan-code/alibaba/ice/packages/rax-compat | petrpan-code/alibaba/ice/packages/rax-compat/tests/createFactory.test.tsx | /**
* @vitest-environment jsdom
*/
import { expect, it, describe } from 'vitest';
import { render } from '@testing-library/react';
import createFactory from '../src/create-factory';
describe('createFactory', () => {
it('basic', () => {
const factory = createFactory('div');
const div = factory(null, 'div node');
const wrapper = render(div);
let res = wrapper.getAllByText('div node');
expect(res.length).toBe(1);
});
});
|
9,681 | 0 | petrpan-code/alibaba/ice/packages/rax-compat | petrpan-code/alibaba/ice/packages/rax-compat/tests/createPortal.test.tsx | /**
* @vitest-environment jsdom
*/
import React from 'react';
import { expect, it, describe } from 'vitest';
import { render } from '@testing-library/react';
import createPortal from '../src/create-portal';
describe('createPortal', () => {
it('basic', () => {
const div = document.createElement('div');
document.body.appendChild(div);
const Portal = ({ children }) => {
return createPortal(children, div);
};
function App() {
return (<div>
<Portal>
<text>Hello Rax</text>
</Portal>
</div>);
}
render(<App />);
expect(div.childNodes.length).toBe(1);
});
});
|
9,682 | 0 | petrpan-code/alibaba/ice/packages/rax-compat | petrpan-code/alibaba/ice/packages/rax-compat/tests/createReactClass.test.tsx | /**
* @vitest-environment jsdom
*/
import { expect, it, describe } from 'vitest';
import * as React from 'react';
import { render } from '@testing-library/react';
import PropTypes from 'prop-types';
import createReactClass from '../src/create-class';
describe('createReactClass', () => {
it('the simplest usage', () => {
const ReactClass = createReactClass({
name: '',
id: '',
render: function () {
return <div data-testid={this.props.id}>Hello, {this.props.name}</div>;
},
});
// @ts-ignore
const wrapper = render(<ReactClass id="reactClassId" name="raxCompat" />);
let res = wrapper.getAllByTestId('reactClassId');
expect(res.length).toBe(1);
});
it('should copy `displayName` onto the Constructor', () => {
const TestComponent = createReactClass({
displayName: 'TestComponent',
render: function () {
return <div />;
},
});
expect(TestComponent.displayName).toBe('TestComponent');
});
it('should support statics', () => {
const Component = createReactClass({
statics: {
abc: 'def',
def: 0,
ghi: null,
jkl: 'mno',
pqr: function () {
return this;
},
},
render: function () {
return <span />;
},
});
// @ts-ignore
expect(Component.abc).toBe('def');
// @ts-ignore
expect(Component.def).toBe(0);
// @ts-ignore
expect(Component.ghi).toBe(null);
// @ts-ignore
expect(Component.jkl).toBe('mno');
// @ts-ignore
expect(Component.pqr()).toBe(Component);
});
it('should work with object getInitialState() return values', () => {
const Component = createReactClass({
getInitialState: function () {
return {
occupation: 'clown',
};
},
render: function () {
return <span data-testid="testerClown">{this.state.occupation}</span>;
},
});
const instance = render(<Component />);
const el = instance.getByTestId('testerClown');
expect(el.innerHTML).toEqual('clown');
});
it('renders based on context getInitialState', () => {
const Foo = createReactClass({
contextTypes: {
className: PropTypes.string,
},
getInitialState() {
return { className: this.context.className };
},
render() {
return <span className={this.state.className} data-testid="testerFoo" />;
},
});
const Outer = createReactClass({
childContextTypes: {
className: PropTypes.string,
},
getChildContext() {
return { className: 'foo' };
},
render() {
return <Foo />;
},
});
const instance = render(<Outer />);
const el = instance.getByTestId('testerFoo');
expect(el.className).toEqual('foo');
});
it('should support statics in mixins', () => {
const Mixin = {
statics: {
foo: 'bar',
},
};
const Component = createReactClass({
mixins: [Mixin],
statics: {
abc: 'def',
},
render: function () {
return <span />;
},
});
render(<Component />);
expect(Component.foo).toBe('bar');
expect(Component.abc).toBe('def');
});
it('should include the mixin keys in even if their values are falsy', () => {
const mixin = {
keyWithNullValue: null,
randomCounter: 0,
};
const Component = createReactClass({
mixins: [mixin],
componentDidMount: function () {
expect(this.randomCounter).toBe(0);
expect(this.keyWithNullValue).toBeNull();
},
render: function () {
return <span />;
},
});
render(<Component />);
});
it('should work with a null getInitialState return value and a mixin', () => {
let Component;
let currentState;
const Mixin = {
getInitialState: function () {
return { foo: 'bar' };
},
};
Component = createReactClass({
mixins: [Mixin],
getInitialState: function () {
return null;
},
render: function () {
currentState = this.state;
return <span />;
},
});
render(<Component />);
expect(currentState).toEqual({ foo: 'bar' });
currentState = null;
// Also the other way round should work
const Mixin2 = {
getInitialState: function () {
return null;
},
};
Component = createReactClass({
mixins: [Mixin2],
getInitialState: function () {
return { foo: 'bar' };
},
render: function () {
currentState = this.state;
return <span />;
},
});
render(<Component />);
expect(currentState).toEqual({ foo: 'bar' });
currentState = null;
// Multiple mixins should be fine too
Component = createReactClass({
mixins: [Mixin, Mixin2],
getInitialState: function () {
return { x: true };
},
render: function () {
currentState = this.state;
return <span />;
},
});
render(<Component />);
expect(currentState).toEqual({ foo: 'bar', x: true });
currentState = null;
});
it('should have bound the mixin methods to the component', () => {
const mixin = {
mixinFunc: function () {
return this;
},
};
const Component = createReactClass({
mixins: [mixin],
componentDidMount: function () {
expect(this.mixinFunc()).toBe(this);
},
render: function () {
return <span />;
},
});
render(<Component />);
});
it('should support mixins with getInitialState()', () => {
let currentState;
const Mixin = {
getInitialState: function () {
return { mixin: true };
},
};
const Component = createReactClass({
mixins: [Mixin],
getInitialState: function () {
return { component: true };
},
render: function () {
currentState = this.state;
return <span />;
},
});
render(<Component />);
expect(currentState.component).toBeTruthy();
expect(currentState.mixin).toBeTruthy();
});
it('should support merging propTypes and statics', () => {
const MixinA = {
propTypes: {
propA: function () {},
},
componentDidMount: function () {
this.props.listener('MixinA didMount');
},
};
const MixinB = {
mixins: [MixinA],
propTypes: {
propB: function () {},
},
componentDidMount: function () {
this.props.listener('MixinB didMount');
},
};
const MixinC = {
statics: {
staticC: function () {},
},
componentDidMount: function () {
this.props.listener('MixinC didMount');
},
};
const MixinD = {
propTypes: {
value: PropTypes.string,
},
};
const Component = createReactClass({
mixins: [MixinB, MixinC, MixinD],
statics: {
staticComponent: function () {},
},
propTypes: {
propComponent: function () {},
},
componentDidMount: function () {
this.props.listener('Component didMount');
},
render: function () {
return <div />;
},
});
const listener = function () {};
render(<Component listener={listener} />);
const instancePropTypes = Component.propTypes;
expect('propA' in instancePropTypes).toBeTruthy();
expect('propB' in instancePropTypes).toBeTruthy();
expect('propComponent' in instancePropTypes).toBeTruthy();
expect('staticC' in Component).toBeTruthy();
expect('staticComponent' in Component).toBeTruthy();
});
});
|
9,683 | 0 | petrpan-code/alibaba/ice/packages/rax-compat | petrpan-code/alibaba/ice/packages/rax-compat/tests/events.test.tsx | /**
* @vitest-environment jsdom
*/
import { expect, it, describe, vi } from 'vitest';
import React from 'react';
import { render } from '@testing-library/react';
import { useRef, useEffect } from '../src/index';
import { createElement } from '../src/create-element';
import findDOMNode from '../src/find-dom-node';
import transformProps from '../src/props';
describe('events', () => {
it('should work with onclick', () => {
function App() {
const ref = useRef(null);
const obj = {
handleClick: () => console.log('click'),
};
const click = vi.spyOn(obj, 'handleClick');
useEffect(() => {
const dom = findDOMNode(ref.current);
dom.click();
expect(click).toHaveBeenCalled();
});
return createElement('div', {
onclick: obj.handleClick,
ref: ref,
}, 'click me');
}
render(<App />);
});
it('should work with ontouchstart', () => {
expect(transformProps({
ontouchstart: () => { },
}).onTouchStart).toBeInstanceOf(Function);
});
it('should work with onclick', () => {
expect(transformProps({
onclick: () => { },
}).onClick).toBeInstanceOf(Function);
expect(transformProps({
onclick: () => { },
}).onclick).toBe(undefined);
});
it('should work with onClick', () => {
expect(transformProps({
onClick: () => { },
}).onClick).toBeInstanceOf(Function);
});
it('should work with ondblclick', () => {
expect(transformProps({
ondblclick: () => { },
}).onDoubleClick).toBeInstanceOf(Function);
expect(transformProps({
ondblclick: () => { },
}).ondblclick).toBe(undefined);
});
it('should work with onDblclick', () => {
expect(transformProps({
onDblclick: () => { },
}).onDoubleClick).toBeInstanceOf(Function);
expect(transformProps({
onDblclick: () => { },
}).onDblclick).toBe(undefined);
});
it('should work with onDoubleClick', () => {
expect(transformProps({
onDoubleClick: () => { },
}).onDoubleClick).toBeInstanceOf(Function);
});
it('should work with onmouseenter', () => {
expect(transformProps({
onmouseenter: () => { },
}).onMouseEnter).toBeInstanceOf(Function);
expect(transformProps({
onmouseenter: () => { },
}).onmouseenter).toBe(undefined);
});
it('should work with onpointerenter', () => {
expect(transformProps({
onpointerenter: () => { },
}).onPointerEnter).toBeInstanceOf(Function);
expect(transformProps({
onpointerenter: () => { },
}).onpointerenter).toBe(undefined);
});
it('should work with onchange', () => {
expect(transformProps({
onchange: () => { },
}).onChange).toBeInstanceOf(Function);
expect(transformProps({
onchange: () => { },
}).onchange).toBe(undefined);
});
it('should work with onbeforeinput', () => {
expect(transformProps({
onbeforeinput: () => { },
}).onBeforeInput).toBeInstanceOf(Function);
expect(transformProps({
onbeforeinput: () => { },
}).onbeforeinput).toBe(undefined);
});
});
|
9,684 | 0 | petrpan-code/alibaba/ice/packages/rax-compat | petrpan-code/alibaba/ice/packages/rax-compat/tests/findDomNode.test.tsx | /**
* @vitest-environment jsdom
*/
import { expect, it, describe } from 'vitest';
import React from 'react';
import { render } from '@testing-library/react';
import { useRef, useEffect } from '../src/index';
import findDOMNode from '../src/find-dom-node';
describe('findDomNode', () => {
it('basic', () => {
const str = 'findDomNode';
function App() {
const ref = useRef(null);
useEffect(() => {
const dom = findDOMNode(ref.current);
expect(dom.textContent).toBe(str);
});
return <div ref={ref} >{str}</div>;
}
render(<App />);
});
});
|
9,685 | 0 | petrpan-code/alibaba/ice/packages/rax-compat | petrpan-code/alibaba/ice/packages/rax-compat/tests/fragment.test.tsx | /**
* @vitest-environment jsdom
*/
import { expect, it, describe } from 'vitest';
import React from 'react';
import { render } from '@testing-library/react';
import Fragment from '../src/fragment';
describe('fragment', () => {
it('basic', () => {
function App() {
return (<Fragment>
<header>A heading</header>
<footer>A footer</footer>
</Fragment>);
}
const wrapper = render(<App />);
expect(wrapper.container.childNodes.length).toBe(2);
});
});
|
9,686 | 0 | petrpan-code/alibaba/ice/packages/rax-compat | petrpan-code/alibaba/ice/packages/rax-compat/tests/hooks.test.tsx | /**
* @vitest-environment jsdom
*/
import { expect, it, describe, vi } from 'vitest';
import React from 'react';
import { render, renderHook } from '@testing-library/react';
import {
useState,
useEffect,
useLayoutEffect,
createContext,
useContext,
useCallback,
useRef,
} from '../src/hooks';
describe('hooks', () => {
it('useState', () => {
function App() {
const [state] = useState({ text: 'text' });
expect(state.text).toBe('text');
return <div>{state.text}</div>;
}
render(<App />);
});
it('useState reset value', () => {
function App() {
const [loading, setLoading] = useState(false);
useEffect(() => {
setLoading(true);
setTimeout(() => {
setLoading(false);
expect(loading).toBe(false);
}, 1);
// Expect useEffect to execute once
// eslint-disable-next-line
}, []);
return <div>{loading ? 'loading...' : 'load end'}</div>;
}
render(<App />);
});
it('useState can be function', () => {
function App() {
const [value] = useState(() => 'useState');
useEffect(() => {
setTimeout(() => {
expect(value).toBe('useState');
}, 1);
// Expect useEffect to execute once
// eslint-disable-next-line
}, []);
return <div>{value}</div>;
}
render(<App />);
});
it('useState update value', () => {
const { result, rerender } = renderHook(() => useState(0));
expect(result.current[0]).toEqual(0);
result.current[1](1);
rerender();
expect(result.current[0]).toEqual(1);
result.current[1]((count) => {
expect(count).toEqual(1);
return count + 10;
});
rerender();
expect(result.current[0]).toEqual(11);
});
it('useEffect', () => {
let useEffectFunc = vi.spyOn({
func: () => {
expect(useEffectFunc).toHaveBeenCalled();
},
}, 'func');
function App() {
useEffect(useEffectFunc, []);
return <div>useEffect</div>;
}
render(<App />);
});
it('useLayoutEffect', () => {
let useEffectFunc = vi.spyOn({
func: () => {
expect(useEffectFunc).toHaveBeenCalled();
},
}, 'func');
function App() {
useLayoutEffect(useEffectFunc, []);
return <div>useEffect</div>;
}
render(<App />);
});
it('useContext', () => {
const Context = createContext({
theme: 'dark',
});
function App() {
const context = useContext(Context);
return <div>{context.theme}</div>;
}
const wrapper = render(<App />);
wrapper.findAllByText('dark').then((res) => {
expect(res.length).toBe(1);
});
});
it('useRef', () => {
function TextInputWithFocusButton() {
const inputEl = useRef(null);
useEffect(() => {
expect(inputEl.current).instanceOf(Element);
});
return (
<>
<input ref={inputEl} type="text" />
</>
);
}
render(<TextInputWithFocusButton />);
});
it('useState x useCallback', () => {
function TextInputWithFocusButton() {
let count = useRef(0);
const [isPassed, setPassed] = useState(false);
const setPassedFalse = useCallback(() => {
setPassed(false);
}, []);
useEffect(() => {
setPassed(true);
}, []);
useEffect(() => {
count.current++;
if (count.current < 10) {
if (count.current % 2) {
expect(isPassed).toBeFalsy();
setPassed(true);
} else {
expect(isPassed).toBeTruthy();
setPassedFalse();
}
}
}, [isPassed, setPassedFalse]);
return <div />;
}
render(<TextInputWithFocusButton />);
});
});
|
9,687 | 0 | petrpan-code/alibaba/ice/packages/rax-compat | petrpan-code/alibaba/ice/packages/rax-compat/tests/inputElement.test.tsx | /**
* @vitest-environment jsdom
*/
import React from 'react';
import { expect, it, describe } from 'vitest';
import { render } from '@testing-library/react';
import { useEffect, useState } from '../src/index';
import { createElement } from '../src/create-element';
describe('inputElement', () => {
it('should work with update input value', () => {
function TestInput() {
const [val, setVal] = useState('input value');
return (<div>
<input
data-testid="inputValue"
value={val}
/>
<div
data-testid="inputValueDiv"
onClick={() => {
setVal('111');
}}
>
click me...
</div>
</div>);
}
const wrapper = render(createElement(TestInput));
wrapper.queryByTestId('inputValueDiv')?.click();
const node = wrapper.queryByTestId('inputValue');
setTimeout(() => {
// Wait for click handler.
expect(node.value).toBe('111');
}, 0);
});
it('inputElement should not recreate when update props', () => {
function TestInput() {
const [val, setVal] = useState('input value');
return (<div>
<input
data-testid="sameInput"
value={val}
/>
<div
data-testid="sameInputDiv"
onClick={() => {
setVal('111');
}}
>
click me...
</div>
</div>);
}
const wrapper = render(createElement(TestInput));
const node = wrapper.queryByTestId('sameInput');
node?.setAttribute('date-value', 'val');
wrapper.queryByTestId('sameInputDiv')?.click();
setTimeout(() => {
// Wait for click handler.
expect(node?.getAttribute('date-value')).toBe('val');
}, 0);
});
it('should work with onChange', () => {
return new Promise((resolve) => {
function TestInput() {
return createElement('input', {
'data-testid': 'changeInput',
onChange: () => resolve(),
});
}
const wrapper = render(createElement(TestInput));
const node = wrapper.queryByTestId('changeInput');
node!.dispatchEvent(new Event('change'));
});
});
it('should work with ref', () => {
return new Promise((resolve) => {
function TestInput() {
const ref = React.useRef();
useEffect(() => {
if (ref.current) {
resolve();
}
}, [ref]);
return createElement('input', {
ref,
});
}
render(createElement(TestInput));
});
});
});
|
9,688 | 0 | petrpan-code/alibaba/ice/packages/rax-compat | petrpan-code/alibaba/ice/packages/rax-compat/tests/isValidElement.test.tsx | /**
* @vitest-environment jsdom
*/
import { expect, it, describe } from 'vitest';
import React from 'react';
import isValidElement from '../src/is-valid-element';
describe('isValidElement', () => {
it('basic', () => {
function App() {
return (<div>
<div>isValidElement</div>
</div>);
}
expect(isValidElement(<App />)).toBe(true);
expect(isValidElement({})).toBe(false);
expect(isValidElement('')).toBe(false);
expect(isValidElement(1)).toBe(false);
expect(isValidElement(() => { })).toBe(false);
});
});
|
9,689 | 0 | petrpan-code/alibaba/ice/packages/rax-compat | petrpan-code/alibaba/ice/packages/rax-compat/tests/props.test.tsx | /**
* @vitest-environment jsdom
*/
import { expect, it, describe } from 'vitest';
import transformProps from '../src/props';
describe('props', () => {
it('should work with autofocus', () => {
expect(transformProps({
autofocus: true,
}).autoFocus).toBe(true);
});
it('should work with autoplay', () => {
expect(transformProps({
autoplay: true,
}).autoPlay).toBe(true);
});
it('should work with classname', () => {
expect(transformProps({
classname: 'class',
}).className).toBe('class');
});
it('should work with crossorigin', () => {
expect(transformProps({
crossorigin: 'xxx',
}).crossOrigin).toBe('xxx');
});
it('should work with maxlength', () => {
expect(transformProps({
maxlength: '10',
}).maxLength).toBe('10');
});
it('should work with inputmode', () => {
expect(transformProps({
inputmode: 'numeric',
}).inputMode).toBe('numeric');
});
});
|
9,690 | 0 | petrpan-code/alibaba/ice/packages/rax-compat | petrpan-code/alibaba/ice/packages/rax-compat/tests/render.test.tsx | /**
* @vitest-environment jsdom
*/
import React from 'react';
import { expect, it, describe } from 'vitest';
import { Component, render } from '../src/index';
describe('render', () => {
it('basic', () => {
class TextComponent extends Component {
render() {
return <div>render text</div>;
}
}
const ele = <TextComponent />;
expect(ele).toBe(render(ele, document.body));
});
});
|
9,691 | 0 | petrpan-code/alibaba/ice/packages/rax-compat | petrpan-code/alibaba/ice/packages/rax-compat/tests/shared.test.tsx | /**
* @vitest-environment jsdom
*/
import { expect, it, describe } from 'vitest';
import React, { forwardRef, useRef, useEffect, Fragment } from 'react';
import { render } from '@testing-library/react';
import { shared } from '../src/index';
import cloneElement from './libs/rax-clone-element';
import createPortal from './libs/rax-create-portal';
import unmountComponentAtNode from './libs/rax-unmount-component-at-node';
describe('shared', () => {
it('base', () => {
expect(typeof shared.Element).toBe('function');
expect(Object.keys(shared.Host).includes('owner')).toBeTruthy();
let node = {};
let instance = {
test: Math.random(),
};
shared.Instance.set(node, instance);
expect(shared.Instance.get(node).test).toBe(instance.test);
expect(shared.flattenChildren).instanceOf(Function);
});
it('create-portal', () => {
const div = document.createElement('div');
document.body.appendChild(div);
const Portal = ({ children }) => {
return createPortal(children, div);
};
const App = () => {
return (<div>
<Portal>portal</Portal>
</div>);
};
render(<App />);
expect(div.childNodes.length).toBe(1);
});
it('unmountComponentAtNode', () => {
const Hello = forwardRef<any, any>(({ name }, ref) => {
return <div>》<span ref={ref}>{ name }</span>《</div>;
});
const Hello2 = forwardRef<any, any>(({ name }, ref) => {
const refin = useRef();
const hello = <Hello name={name} ref={refin} />;
useEffect(() => {
expect(refin.current).toBeUndefined();
}, []);
let ele = cloneElement(hello, {
name: `2-${name}`,
ref,
});
return ele;
});
const App = () => {
const parent = useRef<any>();
const ref = useRef<any>();
useEffect(() => {
ref.current.textContent = '123-by-ref';
unmountComponentAtNode(ref.current);
expect(parent.current.textContent).toBe('》《');
}, []);
return (<div ref={parent}>
<Hello2 name="123" ref={ref} />
</div>);
};
render(<App />);
});
it('flattenChildren null', () => {
// @ts-ignore e
expect(shared.flattenChildren(null)).toBe(null);
});
it('flattenChildren common', () => {
expect(shared.flattenChildren(<>div</>)).toStrictEqual(<Fragment>div</Fragment>);
});
it('flattenChildren array', () => {
const children = [[[<>div</>]]];
expect(shared.flattenChildren(children)).toStrictEqual(<Fragment>div</Fragment>);
});
});
|
9,772 | 0 | petrpan-code/alibaba/ice/packages/runtime | petrpan-code/alibaba/ice/packages/runtime/tests/appConfig.test.ts | import { expect, it, describe } from 'vitest';
import getAppConfig, { defineAppConfig } from '../src/appConfig.js';
describe('AppConfig', () => {
it('getAppConfig', () => {
const appConfig = getAppConfig({
default: {
app: {
rootId: 'app',
},
},
auth: {},
});
expect(appConfig).toStrictEqual({
app: {
rootId: 'app',
strict: false,
},
router: {
type: 'browser',
},
});
});
it('defineAppConfig', () => {
const appConfig = {};
expect(defineAppConfig(appConfig)).toEqual(appConfig);
});
it('defineAppConfig fn', () => {
const appConfig = {};
expect(defineAppConfig(() => appConfig)).toEqual(appConfig);
});
});
|
9,773 | 0 | petrpan-code/alibaba/ice/packages/runtime | petrpan-code/alibaba/ice/packages/runtime/tests/domRender.test.ts | /**
* @vitest-environment jsdom
*/
import { expect, it, describe, afterEach } from 'vitest';
import __ICE__CREATE_ELEMENT from '../src/domRender';
describe('domRender', () => {
afterEach(() => {
document.body.innerHTML = '';
document.head.innerHTML = '';
});
it('basic', () => {
const div = document.createElement('div');
document.body.appendChild(div);
__ICE__CREATE_ELEMENT({
tagName: 'span',
}, div);
expect(div.childNodes.length).toBe(1);
});
it('should work with tagName', () => {
const div = document.createElement('div');
document.body.appendChild(div);
__ICE__CREATE_ELEMENT({
tagName: 'span',
}, div);
expect(div.childNodes[0].tagName).toBe('SPAN');
});
it('should work with children', () => {
const div = document.createElement('div');
document.body.appendChild(div);
__ICE__CREATE_ELEMENT({
tagName: 'div',
children: [
{
tagName: 'span',
},
{
tagName: 'span',
},
{
tagName: 'span',
},
],
}, div);
expect(div.childNodes[0].childNodes.length).toBe(3);
});
it('should work with text', () => {
const div = document.createElement('div');
document.body.appendChild(div);
__ICE__CREATE_ELEMENT({
text: 'text',
}, div);
expect(div.childNodes[0].textContent).toBe('text');
});
it('should work with attribute', () => {
const div = document.createElement('div');
document.body.appendChild(div);
__ICE__CREATE_ELEMENT({
tagName: 'div',
attributes: {
'data-key': 111,
},
}, div);
expect(div.childNodes[0].getAttribute('data-key')).toBe('111');
});
it('should work with head', () => {
__ICE__CREATE_ELEMENT({
tagName: 'meta',
attributes: {
name: 'description',
},
}, document.head);
expect(document.head.childNodes.length).toBe(1);
});
it('should work with body', () => {
__ICE__CREATE_ELEMENT({
tagName: 'meta',
attributes: {
name: 'description',
},
}, document.body);
expect(document.body.childNodes.length).toBe(1);
});
it('should work with child', () => {
const div = document.createElement('div');
document.body.appendChild(div);
__ICE__CREATE_ELEMENT({
tagName: 'div',
children: [
{
tagName: 'span',
},
],
}, div);
expect(div.childNodes[0].childNodes.length).toBe(1);
});
});
|
9,774 | 0 | petrpan-code/alibaba/ice/packages/runtime | petrpan-code/alibaba/ice/packages/runtime/tests/navigator.test.ts | import { expect, it, describe } from 'vitest';
import { createStaticNavigator } from '../src/server/navigator';
describe('mock server navigator', () => {
const staticNavigator = createStaticNavigator();
it('createHref', () => {
expect(staticNavigator.createHref('/')).toBe('/');
});
it('push', () => {
expect(() => staticNavigator.push('/')).toThrow();
});
it('replace', () => {
expect(() => staticNavigator.replace('/')).toThrow();
});
it('go', () => {
expect(() => staticNavigator.go(1)).toThrow();
});
it('back', () => {
expect(() => staticNavigator.back()).toThrow();
});
it('forward', () => {
expect(() => staticNavigator.forward()).toThrow();
});
it('block', () => {
expect(() => staticNavigator.block()).toThrow();
});
}); |
9,775 | 0 | petrpan-code/alibaba/ice/packages/runtime | petrpan-code/alibaba/ice/packages/runtime/tests/proxyData.test.ts | import { expect, it, describe } from 'vitest';
import proxyData from '../src/proxyData';
describe('proxyData', () => {
it('should create a proxy for an object that intercepts property access and mutation', () => {
const testObject = {
name: 'John',
age: 30,
address: {
street: '123 Main St',
city: 'Anytown',
state: 'CA',
zip: '12345',
},
hobbies: ['reading', 'swimming', 'hiking'],
};
const proxy = proxyData(testObject);
expect(proxy.name).toBe('John');
expect(proxy.age).toBe(30);
expect(proxy.address.street).toBe('123 Main St');
expect(proxy.address.city).toBe('Anytown');
expect(proxy.address.state).toBe('CA');
expect(proxy.address.zip).toBe('12345');
expect(proxy.hobbies[0]).toBe('reading');
expect(proxy.hobbies[1]).toBe('swimming');
expect(proxy.hobbies[2]).toBe('hiking');
proxy.name = 'Jane';
expect(proxy.name).toBe('Jane');
proxy.age = 40;
expect(proxy.age).toBe(40);
proxy.address.street = '456 Second St';
expect(proxy.address.street).toBe('456 Second St');
proxy.address.city = 'Newtown';
expect(proxy.address.city).toBe('Newtown');
proxy.address.state = 'NY';
expect(proxy.address.state).toBe('NY');
proxy.address.zip = '67890';
expect(proxy.address.zip).toBe('67890');
proxy.hobbies.push('writing');
expect(proxy.hobbies[3]).toBe('writing');
});
});
|
9,776 | 0 | petrpan-code/alibaba/ice/packages/runtime | petrpan-code/alibaba/ice/packages/runtime/tests/routes.test.tsx | /**
* @vitest-environment jsdom
*/
import React from 'react';
import { renderToString } from 'react-dom/server';
import { expect, it, describe, beforeEach, afterEach, vi } from 'vitest';
import { AppContextProvider } from '../src/AppContext';
import {
RouteComponent,
loadRouteModules,
createRouteLoader,
getRoutesPath,
WrapRouteComponent,
} from '../src/routes.js';
describe('routes', () => {
let windowSpy;
beforeEach(() => {
windowSpy = vi.spyOn(global, 'window', 'get');
});
afterEach(() => {
windowSpy.mockRestore();
});
Object.defineProperty(window, 'open', open);
const homeItem = {
default: () => <></>,
pageConfig: () => ({ title: 'home' }),
dataLoader: { loader: async () => ({ type: 'getData' }) },
serverDataLoader: { loader: async () => ({ type: 'getServerData' }) },
staticDataLoader: { loader: async () => ({ type: 'getStaticData' }) },
};
const aboutItem = {
default: () => <></>,
pageConfig: () => ({ title: 'about' }),
};
const InfoItem = {
default: () => <></>,
pageConfig: () => ({ title: 'home' }),
dataLoader: { loader: async () => ({ type: 'getAsyncData' }), options: { defer: true } },
};
const homeLazyItem = {
Component: homeItem.default,
loader: createRouteLoader({
routeId: 'home',
module: homeItem,
renderMode: 'CSR',
}),
};
const aboutLazyItem = {
Component: aboutItem.default,
loader: createRouteLoader({
routeId: 'about',
module: aboutItem,
renderMode: 'CSR',
}),
};
const routeModules = [
{
id: 'home',
lazy: async () => {
return homeLazyItem;
},
},
{
id: 'about',
lazy: async () => {
return aboutLazyItem;
},
},
];
it('route Component', () => {
const domstring = renderToString(
// @ts-ignore
<AppContextProvider value={{
routeModules: {
home: {
Component: () => <div>home</div>,
},
},
}}
>
<RouteComponent id="home" />
</AppContextProvider>,
);
expect(domstring).toBe('<div>home</div>');
});
it('route error', () => {
const currentEnv = process.env.NODE_ENV;
process.env.NODE_ENV = 'development';
expect(() => renderToString(
// @ts-ignore
<AppContextProvider value={{ routeModules: {} }}>
<RouteComponent id="home" />
</AppContextProvider>,
)).toThrow();
process.env.NODE_ENV = currentEnv;
});
it('route WrapRouteComponent', () => {
const domstring = renderToString(
<AppContextProvider
// @ts-ignore unnecessary to add app context when test WrapRouteComponent.
value={{ RouteWrappers: [{ Wrapper: ({ children }) => <div>wrapper{children}</div>, layout: false }] }}
>
<WrapRouteComponent routeId="test" isLayout={false} routeExports={{ default: () => <div>home</div> }} />
</AppContextProvider>,
);
expect(domstring).toBe('<div>wrapper<div>home</div></div>');
});
it('route WrapRouteComponent match layout', () => {
const domstring = renderToString(
<AppContextProvider
// @ts-ignore unnecessary to add app context when test WrapRouteComponent.
value={{ RouteWrappers: [{ Wrapper: ({ children }) => <div>wrapper{children}</div>, layout: false }] }}
>
<WrapRouteComponent routeId="test" isLayout routeExports={{ default: () => <div>home</div> }} />
</AppContextProvider>,
);
expect(domstring).toBe('<div>home</div>');
});
it('load route modules', async () => {
windowSpy.mockImplementation(() => ({}));
const routeModule = await loadRouteModules(routeModules, {});
expect(routeModule).toStrictEqual({
home: homeLazyItem,
about: aboutLazyItem,
});
});
it('load error module', async () => {
const routeModule = await loadRouteModules([{
id: 'error',
// @ts-ignore
lazy: async () => {
throw new Error('err');
return {};
},
}], {});
expect(routeModule).toStrictEqual({
error: undefined,
});
});
it('load async route', async () => {
const { data: deferredResult } = await createRouteLoader({
routeId: 'home',
module: InfoItem,
})();
const data = await deferredResult.data;
expect(data).toStrictEqual({
type: 'getAsyncData',
});
});
it('load route data for SSG', async () => {
const routesDataSSG = await createRouteLoader({
routeId: 'home',
module: homeItem,
renderMode: 'SSG',
})();
expect(routesDataSSG).toStrictEqual({
data: {
type: 'getStaticData',
},
pageConfig: {
title: 'home',
},
});
});
it('load route data for SSR', async () => {
const routesDataSSR = await createRouteLoader({
routeId: 'home',
module: homeItem,
renderMode: 'SSR',
})();
expect(routesDataSSR).toStrictEqual({
data: {
type: 'getServerData',
},
pageConfig: {
title: 'home',
},
});
});
it('load route data for CSR', async () => {
const routesDataCSR = await createRouteLoader({
routeId: 'home',
module: homeItem,
renderMode: 'CSR',
})();
expect(routesDataCSR).toStrictEqual({
data: {
type: 'getData',
},
pageConfig: {
title: 'home',
},
});
});
it('load data from __ICE_DATA_LOADER__', async () => {
windowSpy.mockImplementation(() => ({
__ICE_DATA_LOADER__: {
getData: async (id) => ({ id: `${id}_data` }),
getLoader: () => {
return {
loader: () => {},
};
},
},
}));
const routesDataCSR = await createRouteLoader({
routeId: 'home',
module: homeItem,
renderMode: 'CSR',
})();
expect(routesDataCSR).toStrictEqual({
data: {
id: 'home_data',
},
pageConfig: {
title: 'home',
},
});
});
it('get routes config without data', async () => {
const routesDataCSR = await createRouteLoader({
routeId: 'about',
module: aboutItem,
renderMode: 'CSR',
})();
expect(routesDataCSR).toStrictEqual({
pageConfig: {
title: 'about',
},
});
});
it('get routes flatten path', () => {
const routes = [
{
path: 'error',
id: 'home',
},
{
id: 'index',
},
];
// @ts-ignore
const result = getRoutesPath(routes);
expect(result).toEqual(['/error', '/']);
});
it('get flatten path of nested routes', () => {
const routes = [
{
id: 'layout',
children: [
{
id: 'home',
path: 'home',
},
{
id: 'layout',
path: 'dashboard',
children: [
{
id: 'about',
path: 'about',
},
{
id: 'blog',
path: 'blog',
},
],
},
],
},
{
id: 'index',
componentName: 'index',
},
];
// @ts-ignore
const result = getRoutesPath(routes);
expect(result).toEqual(['/home', '/dashboard/about', '/dashboard/blog', '/']);
});
});
|
9,777 | 0 | petrpan-code/alibaba/ice/packages/runtime | petrpan-code/alibaba/ice/packages/runtime/tests/routesConfig.test.ts | /**
* @vitest-environment jsdom
*/
import { expect, it, vi, describe, beforeEach, afterEach } from 'vitest';
import { updateRoutesConfig } from '../src/routesConfig';
describe('routes config', () => {
let documentSpy;
const insertTags: any[] = [];
const appendTags: any[] = [];
beforeEach(() => {
documentSpy = vi.spyOn(global, 'document', 'get');
documentSpy.mockImplementation(() => ({
head: {
querySelector: () => ({
content: '',
}),
insertBefore: (tag) => {
insertTags.push(tag);
},
appendChild: (tag) => {
appendTags.push(tag);
tag.onload();
},
},
getElementById: () => null,
querySelectorAll: () => [],
createElement: (type) => {
const element = {
type,
setAttribute: (attr, value) => {
element[attr] = value;
},
};
return element;
},
}));
});
afterEach(() => {
documentSpy.mockRestore();
});
it('update routes config', async () => {
const routesConfig = {
pageConfig: {
title: 'home',
meta: [
{
name: 'theme-color',
content: '#eee',
},
],
links: [{
href: 'https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css',
rel: 'stylesheet',
}],
scripts: [{
src: 'https://cdn.jsdelivr.net/npm/[email protected]/dist/lodash.min.js',
}],
},
};
await updateRoutesConfig(routesConfig);
expect(insertTags.length).toBe(1);
expect(insertTags[0]?.type).toBe('meta');
expect(appendTags.length).toBe(2);
expect(appendTags[0]?.type).toBe('link');
expect(appendTags[1]?.type).toBe('script');
});
});
|
9,778 | 0 | petrpan-code/alibaba/ice/packages/runtime | petrpan-code/alibaba/ice/packages/runtime/tests/runClientApp.test.tsx | /**
* @vitest-environment jsdom
*/
import React from 'react';
import { renderToString } from 'react-dom/server';
import { expect, it, vi, describe, beforeEach, afterEach } from 'vitest';
import { fetch, Request, Response } from '@remix-run/web-fetch';
import runClientApp from '../src/runClientApp';
import { useAppData } from '../src/AppContext';
describe('run client app', () => {
let windowSpy;
let documentSpy;
if (!globalThis.fetch) {
// @ts-expect-error
globalThis.fetch = fetch;
// @ts-expect-error
globalThis.Request = Request;
// @ts-expect-error
globalThis.Response = Response;
}
const mockData = {
location: new URL('http://localhost:4000/'),
history: {
replaceState: vi.fn(),
},
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
};
beforeEach(() => {
process.env.ICE_CORE_ROUTER = 'true';
windowSpy = vi.spyOn(global, 'window', 'get');
documentSpy = vi.spyOn(global, 'document', 'get');
windowSpy.mockImplementation(() => mockData);
documentSpy.mockImplementation(() => ({
head: {
querySelector: () => ({
content: '',
}),
},
body: {
appendChild: () => null,
},
getElementById: () => null,
createElement: () => ({
id: '',
}),
querySelectorAll: () => [],
}));
});
afterEach(() => {
(window as any).__ICE_DATA_LOADER__ = undefined;
windowSpy.mockRestore();
documentSpy.mockRestore();
});
let domstring = '';
const serverRuntime = async ({ setRender }) => {
setRender((container, element) => {
try {
domstring = renderToString(element as any);
} catch (err) {
domstring = '';
}
});
};
let staticMsg = '';
const staticRuntime = async () => {
staticMsg = 'static';
};
const providerRuntmie = async ({ addProvider }) => {
const Provider = ({ children }) => {
return <div>{children}</div>;
};
addProvider(Provider);
// Add twice.
addProvider(Provider);
};
const homeItem = {
default: () => {
// eslint-disable-next-line react-hooks/rules-of-hooks
const appData = useAppData();
return (
<div>home{appData?.msg || ''}</div>
);
},
pageConfig: () => ({ title: 'home' }),
dataLoader: {
loader: async () => ({ data: 'test' }),
},
};
const basicRoutes = [
{
id: 'home',
path: '/',
componentName: 'Home',
lazy: () => {
return {
Component: homeItem.default,
};
},
},
];
it('run with static runtime', async () => {
await runClientApp({
app: {
dataLoader: {
loader: async () => {
return { msg: staticMsg };
},
},
},
// @ts-ignore don't need to pass params in test case.
createRoutes: () => basicRoutes,
runtimeModules: { commons: [serverRuntime], statics: [staticRuntime] },
hydrate: true,
});
expect(domstring).toBe('<div>home<!-- -->static</div>');
});
it('run client basic', async () => {
windowSpy.mockImplementation(() => ({
...mockData,
location: new URL('http://localhost:4000/?test=1&runtime=true&baisc'),
}));
await runClientApp({
app: {},
// @ts-ignore don't need to pass params in test case.
createRoutes: () => basicRoutes,
runtimeModules: { commons: [serverRuntime] },
hydrate: false,
});
expect(domstring).toBe('<div>home</div>');
});
it('run client single-router', async () => {
const sigleRoutes = [
{
id: 'home',
path: '/',
lazy: () => {
return {
Component: homeItem.default,
loader: () => {},
};
},
},
];
process.env.ICE_CORE_ROUTER = '';
await runClientApp({
app: {},
// @ts-ignore don't need to pass params in test case.
createRoutes: () => sigleRoutes,
runtimeModules: { commons: [serverRuntime] },
hydrate: false,
});
process.env.ICE_CORE_ROUTER = 'true';
expect(domstring).toBe('<div>home</div>');
});
it('run client with app provider', async () => {
await runClientApp({
app: {},
// @ts-ignore don't need to pass params in test case.
createRoutes: () => basicRoutes,
runtimeModules: { commons: [serverRuntime, providerRuntmie] },
hydrate: true,
});
expect(domstring).toBe('<div><div><div>home</div></div></div>');
});
it('run client with memory router', async () => {
const routes = [...basicRoutes, {
id: 'about',
path: '/about',
componentName: 'About',
Component: () => {
return (
<div>about</div>
);
} }];
await runClientApp({
app: {
default: {
router: {
type: 'memory',
initialEntries: ['/about'],
},
},
},
// @ts-ignore don't need to pass params in test case.
createRoutes: () => routes,
runtimeModules: { commons: [serverRuntime] },
hydrate: true,
});
expect(domstring).toBe('<div>about</div>');
await runClientApp({
app: {
default: {
},
},
// @ts-ignore don't need to pass params in test case.
createRoutes: () => basicRoutes,
runtimeModules: { commons: [serverRuntime] },
hydrate: true,
});
});
it('run client with memory router - from context', async () => {
windowSpy.mockImplementation(() => ({
...mockData,
__ICE_APP_CONTEXT__: {
routePath: '/about',
},
}));
const routes = [...basicRoutes, {
id: 'about',
path: '/about',
componentName: 'About',
Component: () => {
return (
<div>about</div>
);
} }];
await runClientApp({
app: {
},
// @ts-ignore don't need to pass params in test case.
createRoutes: () => routes,
runtimeModules: { commons: [serverRuntime] },
hydrate: true,
memoryRouter: true,
});
expect(domstring).toBe('<div>about</div>');
});
it('run client with hash router', async () => {
await runClientApp({
app: {
default: {
router: {
type: 'hash',
},
},
},
// @ts-ignore don't need to pass params in test case.
createRoutes: () => basicRoutes,
runtimeModules: { commons: [serverRuntime] },
hydrate: true,
});
expect(domstring).toBe('<div>home</div>');
});
it('run client with app data', async () => {
let executed = false;
await runClientApp({
app: {
dataLoader: {
loader: async () => {
executed = true;
return { msg: '-getAppData' };
},
},
},
// @ts-ignore don't need to pass params in test case.
createRoutes: () => basicRoutes,
runtimeModules: { commons: [serverRuntime] },
hydrate: false,
});
expect(domstring).toBe('<div>home<!-- -->-getAppData</div>');
expect(executed).toBe(true);
});
it('run client with app data', async () => {
let useGlobalLoader = false;
let executed = false;
windowSpy.mockImplementation(() => ({
...mockData,
__ICE_DATA_LOADER__: {
getData: async () => {
useGlobalLoader = true;
return { msg: '-globalData' };
},
},
}));
await runClientApp({
app: {
dataLoader: {
loader: async () => {
executed = true;
return { msg: 'app' };
},
},
},
// @ts-ignore don't need to pass params in test case.
createRoutes: () => basicRoutes,
runtimeModules: { commons: [serverRuntime] },
hydrate: false,
});
expect(executed).toBe(false);
expect(useGlobalLoader).toBe(true);
expect(domstring).toBe('<div>home<!-- -->-globalData</div>');
});
it('run client with AppErrorBoundary', async () => {
await runClientApp({
app: {
default: {
app: {
errorBoundary: true,
},
},
},
// @ts-ignore don't need to pass params in test case.
createRoutes: () => basicRoutes,
runtimeModules: { commons: [serverRuntime] },
hydrate: false,
});
expect(domstring).toBe('<div>home</div>');
});
});
|
9,779 | 0 | petrpan-code/alibaba/ice/packages/runtime | petrpan-code/alibaba/ice/packages/runtime/tests/runServerApp.test.tsx | /**
* @vitest-environment jsdom
*/
import React from 'react';
import { expect, it, describe } from 'vitest';
import { renderToHTML, renderToResponse } from '../src/runServerApp';
import { Meta, Title, Links, Main, Scripts, usePageAssets } from '../src/Document';
import { useAppContext } from '../src/';
import {
createRouteLoader,
} from '../src/routes.js';
describe('run server app', () => {
process.env.ICE_CORE_ROUTER = 'true';
const homeItem = {
default: () => <div>home</div>,
pageConfig: () => ({ title: 'home' }),
dataLoader: {
loader: async () => ({ data: 'test' }),
},
};
const basicRoutes = [
{
id: 'home',
path: 'home',
componentName: 'home',
lazy: () => {
return {
Component: homeItem.default,
loader: createRouteLoader({
routeId: 'home',
module: homeItem,
renderMode: 'SSR',
}),
};
},
},
];
const assetsManifest = {
publicPath: '/',
assets: {},
entries: [],
pages: {
home: ['js/home.js'],
},
};
const Document = () => (
<html>
<head>
<meta charSet="utf-8" />
<meta name="description" content="ICE 3.0 Demo" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<Meta />
<Title />
<Links />
</head>
<body>
<Main />
<Scripts />
</body>
</html>
);
it('render to html', async () => {
const html = await renderToHTML({
// @ts-ignore
req: {
url: '/home',
},
}, {
app: {},
assetsManifest,
runtimeModules: { commons: [] },
// @ts-ignore don't need to pass params in test case.
createRoutes: () => basicRoutes,
Document,
renderMode: 'SSR',
});
// @ts-ignore
expect(html?.value?.includes('<div>home</div>')).toBe(true);
// @ts-ignore
expect(html?.value?.includes('js/home.js')).toBe(true);
});
it('render with full url', async () => {
const html = await renderToHTML({
// @ts-ignore
req: {
url: 'http://some.proxy:9988/home?foo=bar',
},
}, {
app: {},
assetsManifest,
runtimeModules: { commons: [] },
routes: basicRoutes,
// @ts-ignore don't need to pass params in test case.
createRoutes: () => basicRoutes,
Document,
renderMode: 'SSR',
});
// @ts-ignore
expect(html?.statusCode).toBe(200);
});
it('render to html basename', async () => {
const html = await renderToHTML({
// @ts-ignore
req: {
url: '/home',
},
}, {
app: {},
assetsManifest,
runtimeModules: { commons: [] },
// @ts-ignore don't need to pass params in test case.
createRoutes: () => basicRoutes,
Document,
renderMode: 'SSR',
basename: '/ice',
});
// @ts-ignore
expect(html?.statusCode).toBe(404);
});
it('render to html serverOnlyBasename', async () => {
const html = await renderToHTML({
// @ts-ignore
req: {
url: '/home',
},
}, {
app: {},
assetsManifest,
runtimeModules: { commons: [] },
// @ts-ignore don't need to pass params in test case.
createRoutes: () => basicRoutes,
Document,
renderMode: 'SSR',
serverOnlyBasename: '/',
basename: '/ice',
});
// @ts-ignore
expect(html?.statusCode).toBe(200);
});
it('render to 404 html', async () => {
const html = await renderToHTML({
// @ts-ignore
req: {
url: '/about',
},
}, {
app: {},
assetsManifest,
runtimeModules: { commons: [] },
// @ts-ignore don't need to pass params in test case.
createRoutes: () => basicRoutes,
Document,
});
// @ts-ignore
expect(html?.statusCode).toBe(404);
});
it('router hash', async () => {
const html = await renderToHTML({
// @ts-ignore
req: {
url: '/home',
},
}, {
app: {
default: {
router: {
type: 'hash',
},
},
},
assetsManifest,
runtimeModules: { commons: [] },
// @ts-ignore don't need to pass params in test case.
createRoutes: () => basicRoutes,
Document,
});
// @ts-ignore
expect(html?.statusCode).toBe(200);
// @ts-ignore
expect(html?.value?.includes('<div>home</div>')).toBe(false);
});
it('fallback to csr', async () => {
const html = await renderToHTML({
// @ts-ignore
req: {
url: '/home',
},
}, {
app: {},
assetsManifest,
runtimeModules: { commons: [] },
// @ts-ignore don't need to pass params in test case.
createRoutes: () => [{
id: 'home',
path: 'home',
componentName: 'Home',
lazy: () => {
return {
Component: () => {
throw new Error('err');
return (
<div>home</div>
);
},
loader: () => {
return { data: {}, pageConfig: {} };
},
};
},
}],
Document,
});
// @ts-ignore
expect(html?.value?.includes('<div>home</div>')).toBe(false);
});
it('render to response', async () => {
let htmlContent = '';
await renderToResponse({
// @ts-ignore
req: {
url: '/home',
},
res: {
destination: {},
// @ts-ignore
setHeader: () => { },
// @ts-ignore
end: (content) => {
htmlContent = content;
},
},
}, {
app: {},
assetsManifest,
runtimeModules: { commons: [] },
// @ts-ignore don't need to pass params in test case.
createRoutes: () => basicRoutes,
Document,
renderMode: 'SSR',
routePath: '/',
documentOnly: true,
});
expect(!!htmlContent).toBe(true);
expect(htmlContent.includes('<div>home</div')).toBe(false);
});
it('render with use scripts', async () => {
let scripts;
let renderMode;
const Document = () => {
scripts = usePageAssets();
const context = useAppContext();
renderMode = context.renderMode;
return (
<html>
<head>
<meta charSet="utf-8" />
<meta name="description" content="ICE 3.0 Demo" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<Meta />
<Title />
<Links />
</head>
<body>
<Main />
<Scripts />
</body>
</html>
);
};
const html = await renderToHTML({
// @ts-ignore
req: {
url: '/home',
},
}, {
app: {},
assetsManifest,
runtimeModules: { commons: [] },
// @ts-ignore don't need to pass params in test case.
createRoutes: () => basicRoutes,
Document,
renderMode: 'SSR',
});
// @ts-ignore
expect(html?.value?.includes('<div>home</div>')).toBe(true);
// @ts-ignore
expect(html?.value?.includes('js/home.js')).toBe(true);
expect(scripts).toStrictEqual(['/js/home.js']);
expect(renderMode).toBe('SSR');
});
});
|
9,780 | 0 | petrpan-code/alibaba/ice/packages/runtime | petrpan-code/alibaba/ice/packages/runtime/tests/singleRoute.test.tsx | import React from 'react';
import { expect, it, describe } from 'vitest';
import {
useRoutes,
Router,
createHistory,
matchRoutes,
Link,
Outlet,
useParams,
useSearchParams,
useLocation,
useNavigate,
} from '../src/singleRouter';
describe('single route api', () => {
it('useRoutes', () => {
expect(useRoutes([{ element: <div>test</div> }])).toStrictEqual(
<React.Fragment>
<div>
test
</div>
</React.Fragment>);
});
it('Router', () => {
expect(Router({ children: <div>test</div> })).toStrictEqual(
<React.Fragment>
<div>
test
</div>
</React.Fragment>);
});
it('createHistory', () => {
expect(createHistory().location).toBe('');
});
it('matchRoutes - single route', () => {
const routes = [
{
path: 'users',
element: <div>user</div>,
},
];
const location = {
pathname: '/test',
};
const matchedRoutes = matchRoutes(routes, location, '/');
expect(matchedRoutes).toHaveLength(1);
expect(matchedRoutes[0].route.path).toBe('users');
});
it('matchRoutes - mutiple route', () => {
const routes = [
{
path: 'users',
element: <div>user</div>,
},
{
path: 'posts',
element: <div>post</div>,
},
];
const location = {
pathname: '/posts',
};
const matchedRoutes = matchRoutes(routes, location, '/');
expect(matchedRoutes).toHaveLength(1);
expect(matchedRoutes[0].route.path).toBe('posts');
});
it('matchRoutes - basename', () => {
const routes = [
{
path: 'users',
element: <div>user</div>,
},
{
path: 'posts',
element: <div>post</div>,
},
];
const matchedRoutes = matchRoutes(routes, '/basename/posts', '/basename');
expect(matchedRoutes).toHaveLength(1);
expect(matchedRoutes[0].route.path).toBe('posts');
});
it('Link', () => {
expect(Link()).toBe(null);
});
it('Outlet', () => {
expect(Outlet()).toStrictEqual(<React.Fragment />);
});
it('useParams', () => {
expect(useParams()).toStrictEqual({});
});
it('useSearchParams', () => {
expect(useSearchParams()[0]).toStrictEqual({});
});
it('useLocation', () => {
expect(useLocation()).toStrictEqual({});
});
it('useNavigate', () => {
expect(useNavigate()).toStrictEqual({});
});
});
|
9,781 | 0 | petrpan-code/alibaba/ice/packages/runtime | petrpan-code/alibaba/ice/packages/runtime/tests/templateParse.test.ts | /**
* @vitest-environment jsdom
*/
import { expect, it, describe, beforeEach, afterEach, vi } from 'vitest';
import { parseTemplate } from '../src/dataLoader';
describe('parseTemplate', () => {
let locationSpy;
let documentSpy;
let localStorageSpy;
beforeEach(() => {
locationSpy = vi.spyOn(global, 'location', 'get');
documentSpy = vi.spyOn(global, 'document', 'get');
localStorageSpy = vi.spyOn(global, 'localStorage', 'get');
locationSpy.mockImplementation(() => {
return {
search: '?queryKey=queryValue',
href: 'https://localhost:3000',
};
});
documentSpy.mockImplementation(() => {
return {
cookie: 'cookieKey=cookieValue;',
};
});
localStorageSpy.mockImplementation(() => {
return {
getItem: () => 'storageValue',
};
});
});
afterEach(() => {
locationSpy.mockRestore();
documentSpy.mockRestore();
});
it('should work with queryParams', () => {
expect(parseTemplate({
key: 'prefetchKey',
prefetch_type: 'xxx',
api: 'xxx.xxx',
v: '1.0.0',
data: {
templateData: '${queryParams.queryKey}',
},
ext_headers: {},
})).toStrictEqual({
key: 'prefetchKey',
prefetch_type: 'xxx',
api: 'xxx.xxx',
v: '1.0.0',
data: {
templateData: 'queryValue',
},
ext_headers: {},
});
});
it('should work with cookie', () => {
expect(parseTemplate({
key: 'prefetchKey',
prefetch_type: 'xxx',
api: 'xxx.xxx',
v: '1.0.0',
data: {
templateData: '${cookie.cookieKey}',
},
ext_headers: {},
})).toStrictEqual({
key: 'prefetchKey',
prefetch_type: 'xxx',
api: 'xxx.xxx',
v: '1.0.0',
data: {
templateData: 'cookieValue',
},
ext_headers: {},
});
});
it('should work with href', () => {
expect(parseTemplate({
key: 'prefetchKey',
prefetch_type: 'xxx',
api: 'xxx.xxx',
v: '1.0.0',
data: {
templateData: '${url}',
},
ext_headers: {},
})).toStrictEqual({
key: 'prefetchKey',
prefetch_type: 'xxx',
api: 'xxx.xxx',
v: '1.0.0',
data: {
templateData: 'https://localhost:3000',
},
ext_headers: {},
});
});
it('should work with storage', () => {
expect(parseTemplate({
key: 'prefetchKey',
prefetch_type: 'xxx',
api: 'xxx.xxx',
v: '1.0.0',
data: {
templateData: '${storage.storageKey}',
},
ext_headers: {},
})).toStrictEqual({
key: 'prefetchKey',
prefetch_type: 'xxx',
api: 'xxx.xxx',
v: '1.0.0',
data: {
templateData: 'storageValue',
},
ext_headers: {},
});
});
}); |
9,798 | 0 | petrpan-code/alibaba/ice/packages/shared-config | petrpan-code/alibaba/ice/packages/shared-config/tests/redirectImport.test.ts | import * as path from 'path';
import * as fs from 'fs';
import { fileURLToPath } from 'url';
import { expect, describe, it } from 'vitest';
import { redirectImport } from '../src/unPlugins/redirectImport';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
describe('redirect import', () => {
const exportData = [{
specifier: ['runApp'],
source: '@ice/runtime',
}, {
specifier: 'Head',
source: 'react-helmet',
alias: {
Head: 'Helmet',
},
}, {
specifier: 'store',
source: '@ice/store',
}, {
specifier: ['request', 'test'],
source: 'axios',
}];
it('basic transform', async () => {
const code = fs.readFileSync(path.join(__dirname, './fixtures/redirectImport/basic.js'), 'utf-8');
const transformed = await redirectImport(code, { exportData, targetSource: 'ice' });
expect(transformed).toBe('import { runApp } from \'@ice/runtime\';');
});
it('as transform', async () => {
const code = fs.readFileSync(path.join(__dirname, './fixtures/redirectImport/as.js'), 'utf-8');
const transformed = await redirectImport(code, { exportData, targetSource: 'ice' });
expect(transformed).toBe('import { runApp as run } from \'@ice/runtime\';');
});
it('alias transform', async () => {
const code = fs.readFileSync(path.join(__dirname, './fixtures/redirectImport/alias.js'), 'utf-8');
const transformed = await redirectImport(code, { exportData, targetSource: 'ice' });
expect(transformed).toBe('import Helmet as Head from \'react-helmet\';');
});
it('alias with as transform', async () => {
const code = fs.readFileSync(path.join(__dirname, './fixtures/redirectImport/aliasWithAs.js'), 'utf-8');
const transformed = await redirectImport(code, { exportData, targetSource: 'ice' });
expect(transformed).toBe('import Helmet as Header from \'react-helmet\';');
});
it('multiple transform', async () => {
const code = fs.readFileSync(path.join(__dirname, './fixtures/redirectImport/multiple.js'), 'utf-8');
const transformed = await redirectImport(code, { exportData, targetSource: 'ice' });
expect(transformed).toBe('import { request, test } from \'axios\';\nimport store from \'@ice/store\';');
});
it('matched transform', async () => {
const code = fs.readFileSync(path.join(__dirname, './fixtures/redirectImport/matched.js'), 'utf-8');
const transformed = await redirectImport(code, { exportData, targetSource: 'ice' });
expect(transformed).toBe('import { defineDataLoader } from \'ice\';\nimport { runApp } from \'@ice/runtime\';');
});
it('missmatched transform', async () => {
const code = fs.readFileSync(path.join(__dirname, './fixtures/redirectImport/missmatch.js'), 'utf-8');
const transformed = await redirectImport(code, { exportData, targetSource: 'ice' });
expect(transformed).toBe('import { defineDataLoader } from \'ice\';');
});
});
|
9,799 | 0 | petrpan-code/alibaba/ice/packages/shared-config | petrpan-code/alibaba/ice/packages/shared-config/tests/transformImport.test.ts | import * as path from 'path';
import * as fs from 'fs';
import { fileURLToPath } from 'url';
import { expect, describe, it } from 'vitest';
import transformImport from '../src/utils/transformImport';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
describe('transform core js path', () => {
const coreJsPath = '/path/to/core-js/';
it('matched', async () => {
const orignalCode = fs.readFileSync(path.join(__dirname, './fixtures/transformImport/match.js'), 'utf-8');
expect(await transformImport(orignalCode, coreJsPath))
.toBe('import \'/path/to/core-js/modules/test\';import \'react\';');
});
it('matched esm', async () => {
const orignalCode = fs.readFileSync(path.join(__dirname, './fixtures/transformImport/esm.js'), 'utf-8');
expect(await transformImport(orignalCode, coreJsPath))
.toBe('import \'/path/to/core-js/modules/test\';export default \'a\';');
});
it('matched cjs', async () => {
const orignalCode = fs.readFileSync(path.join(__dirname, './fixtures/transformImport/cjs.js'), 'utf-8');
expect(await transformImport(orignalCode, coreJsPath))
.toBe('require (\'/path/to/core-js/modules/test\');module.exports = {};');
});
it('miss match', async () => {
const orignalCode = fs.readFileSync(path.join(__dirname, './fixtures/transformImport/missmatch.js'), 'utf-8');
expect(await transformImport(orignalCode, coreJsPath))
.toBe('import \'react\';');
});
it('string included', async () => {
const orignalCode = fs.readFileSync(path.join(__dirname, './fixtures/transformImport/stringInclude.js'), 'utf-8');
expect(await transformImport(orignalCode, coreJsPath))
.toBe('import \'somepack/core-js/modules/test\';import \'react\';');
});
it('@swc/helpers esm', async () => {
const orignalCode = fs.readFileSync(path.join(__dirname, './fixtures/transformImport/swc-esm.js'), 'utf-8');
expect(await transformImport(orignalCode, coreJsPath))
.toBe('import { _ as _object_spread } from \'@swc/helpers/_/_object_spread\';import \'react\';');
});
it('@swc/helpers cjs', async () => {
const orignalCode = fs.readFileSync(path.join(__dirname, './fixtures/transformImport/swc.js'), 'utf-8');
expect(await transformImport(orignalCode, coreJsPath))
.toBe('var _object_spread = require(\'@swc/helpers/cjs/_object_spread.cjs\')._;module.exports = {};');
});
it('@swc/helpers special identifier', async () => {
const orignalCode = fs.readFileSync(path.join(__dirname, './fixtures/transformImport/specialIdentifier.js'), 'utf-8');
expect(await transformImport(orignalCode, coreJsPath))
.toBe('var _create_class = require(\'@swc/helpers/cjs/_create_class.cjs\')._;module.exports = {};');
});
it('with import.meta', async () => {
const orignalCode = fs.readFileSync(path.join(__dirname, './fixtures/transformImport/importMeta.js'), 'utf-8');
expect(await transformImport(orignalCode, coreJsPath))
.toBe('if (import.meta.rerender === \'client\') console.log(true);');
});
});
|
9,833 | 0 | petrpan-code/alibaba/ice/packages/style-import | petrpan-code/alibaba/ice/packages/style-import/tests/importStyle.test.ts | import { expect, it, describe } from 'vitest';
import { importStyle } from '../src/index';
describe('import style', () => {
it('simple import', async () => {
const sourceCode = 'import { Button } from \'antd\';';
const result = await importStyle(sourceCode, { libraryName: 'antd', style: true });
expect(result?.code).toBe(`${sourceCode}\nimport 'antd/es/button/style';`);
});
it('custom style', async () => {
const sourceCode = 'import { Button } from \'antd\';';
const result = await importStyle(sourceCode, { libraryName: 'antd', style: (name) => `antd/es/${name.toLocaleLowerCase()}/style` });
expect(result?.code).toBe(`${sourceCode}\nimport 'antd/es/button/style';`);
});
it('mismatch import', async () => {
const sourceCode = 'import { Button } from \'antd-mobile\';';
const result = await importStyle(sourceCode, { libraryName: 'antd', style: true });
expect(result?.code).toBe(`${sourceCode}`);
});
it('multiple import', async () => {
const sourceCode = 'import { Button, Table } from \'antd\';';
const result = await importStyle(sourceCode, { libraryName: 'antd', style: true });
expect(result?.code).toBe(`${sourceCode}\nimport 'antd/es/button/style';\nimport 'antd/es/table/style';`);
});
it('named import', async () => {
const sourceCode = 'import { Button as Btn } from \'antd\';';
const result = await importStyle(sourceCode, { libraryName: 'antd', style: true });
expect(result?.code).toBe(`${sourceCode}\nimport 'antd/es/button/style';`);
});
it('default import', async () => {
const sourceCode = 'import * as antd from \'antd\';';
const result = await importStyle(sourceCode, { libraryName: 'antd', style: true });
expect(result?.code).toBe(`${sourceCode}`);
});
it('sourcemap', async () => {
const sourceCode = 'import * as antd from \'antd\';';
const result = await importStyle(sourceCode, { libraryName: 'antd', style: true, sourceMap: true });
expect(!!result?.map).toBe(true);
});
it('none import', async () => {
const sourceCode = 'export const a = \'antd\';';
const result = await importStyle(sourceCode, { libraryName: 'antd', style: true });
expect(result).toBe(null);
});
it('parse error', async () => {
const sourceCode = 'export antd, { Button } from \'antd\';';
const result = await importStyle(sourceCode, { libraryName: 'antd', style: true });
expect(result).toBe(null);
});
it('import error', async () => {
const sourceCode = 'import antd, { Button } from \'antd\';';
const result = await importStyle(sourceCode, { libraryName: 'antd', style: true });
expect(result?.code).toBe(sourceCode);
});
it('style false', async () => {
const sourceCode = 'import { Button } from \'antd\';';
const result = await importStyle(sourceCode, { libraryName: 'antd', style: false });
expect(result).toBe(null);
});
});
|
9,850 | 0 | petrpan-code/alibaba/ice/packages/webpack-modify | petrpan-code/alibaba/ice/packages/webpack-modify/tests/api.test.ts | import { expect, it, describe } from 'vitest';
import type { Configuration } from 'webpack';
import { removeLoader, addLoader, modifyLoader, modifyRule, removePlugin } from '../src/index';
describe('test webpack config modify', () => {
const getWebpackConfig = () => ({
module: {
rules: [
{
test: /.css$/,
use: [
{
loader: '/absoulte/path/to/postcss-loader',
},
{
loader: '/absoulte/path/to/css-loader',
},
],
},
],
},
});
it('remove loader', () => {
const webpackConfig: Configuration = getWebpackConfig();
expect(removeLoader(webpackConfig, {
rule: '.css',
loader: 'css-loader',
})).toStrictEqual({
module: {
rules: [{
test: /.css$/,
use: [
{
loader: '/absoulte/path/to/postcss-loader',
},
],
}],
},
});
});
it('add loader', () => {
expect(addLoader(getWebpackConfig(), {
rule: '.css',
useItem: {
loader: 'custom-loader',
},
before: 'css-loader',
})).toStrictEqual({
module: {
rules: [{
test: /.css$/,
use: [
{
loader: '/absoulte/path/to/postcss-loader',
},
{
loader: 'custom-loader',
},
{
loader: '/absoulte/path/to/css-loader',
},
],
}],
},
});
expect(addLoader(getWebpackConfig(), {
rule: '.css',
useItem: {
loader: 'custom-loader',
},
after: 'css-loader',
})).toStrictEqual({
module: {
rules: [{
test: /.css$/,
use: [
{
loader: '/absoulte/path/to/postcss-loader',
},
{
loader: '/absoulte/path/to/css-loader',
},
{
loader: 'custom-loader',
},
],
}],
},
});
});
it('modify loader', () => {
expect(modifyLoader(getWebpackConfig(), {
rule: '.css',
loader: 'css-loader',
options: () => ({ module: true }),
})).toStrictEqual({
module: {
rules: [{
test: /.css$/,
use: [
{
loader: '/absoulte/path/to/postcss-loader',
},
{
loader: '/absoulte/path/to/css-loader',
options: { module: true },
},
],
}],
},
});
});
it('modify rule', () => {
const webpackConfig = getWebpackConfig();
webpackConfig.module.rules.push({
test: /.less/,
use: [],
});
expect(modifyRule(webpackConfig, {
rule: '.css',
options: () => ({
test: /.css$/,
use: [],
}),
})).toStrictEqual({
module: {
rules: [{
test: /.css$/,
use: [],
}, {
test: /.less/,
use: [],
}],
},
});
});
it('remove plugin', () => {
class TestPlugin {}
expect(removePlugin({
plugins: [
// @ts-ignore fake webpack plugin
new TestPlugin(),
],
}, 'TestPlugin')).toStrictEqual({
plugins: [],
});
});
it('miss loader', () => {
expect(removeLoader(getWebpackConfig(), {
rule: '.css',
loader: 'test-loader',
})).toStrictEqual(getWebpackConfig());
expect(removeLoader(getWebpackConfig(), {
rule: '.test',
loader: 'css-loader',
})).toStrictEqual(getWebpackConfig());
});
}); |
9,854 | 0 | petrpan-code/alibaba/ice/tests | petrpan-code/alibaba/ice/tests/integration/app-config.test.ts | import { expect, test, describe, afterAll } from 'vitest';
import { buildFixture, setupBrowser } from '../utils/build';
import { startFixture, setupStartBrowser } from '../utils/start';
import type { Page } from '../utils/browser';
import type Browser from '../utils/browser';
const example = 'app-config';
describe(`build ${example}`, () => {
test('open /', async () => {
await buildFixture(example);
await setupBrowser({ example });
});
});
describe(`start ${example}`, () => {
let page: Page;
let browser: Browser;
test('setup devServer', async () => {
const { devServer, port } = await startFixture(example);
const res = await setupStartBrowser({ server: devServer, port });
page = res.page;
browser = res.browser;
await page.push('/ice');
expect(await page.$$text('h1')).toStrictEqual(['home']);
});
test('error page', async () => {
await page.push('/ice/error');
await page.waitForNetworkIdle();
expect(await page.$$text('h1')).toStrictEqual(['Something went wrong.']);
});
afterAll(async () => {
await browser.close();
});
});
describe(`start ${example} in speedup mode`, () => {
let page: Page;
let browser: Browser;
test('open /', async () => {
const { devServer, port } = await startFixture(example, { speedup: true });
const res = await setupStartBrowser({ server: devServer, port });
page = res.page;
browser = res.browser;
await page.push('/ice');
expect(await page.$$text('h1')).toStrictEqual(['home']);
});
afterAll(async () => {
await browser.close();
});
});
describe(`build ${example} in speedup mode`, () => {
test('open /', async () => {
await buildFixture(example, { speedup: true });
});
});
|
9,855 | 0 | petrpan-code/alibaba/ice/tests | petrpan-code/alibaba/ice/tests/integration/basic-project.test.ts | import * as path from 'path';
import * as fs from 'fs';
import { fileURLToPath } from 'url';
import { expect, test, describe, afterAll } from 'vitest';
import { buildFixture, setupBrowser } from '../utils/build';
import { startFixture, setupStartBrowser } from '../utils/start';
import type { Page } from '../utils/browser';
import type Browser from '../utils/browser';
// @ts-ignore
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const example = 'basic-project';
describe(`build ${example}`, () => {
let page: Page;
let browser: Browser;
test('open /', async () => {
await buildFixture(example);
const res = await setupBrowser({ example });
page = res.page;
browser = res.browser;
expect(await page.$$text('h2')).toStrictEqual(['Home Page']);
expect(await page.$$text('#data-from')).toStrictEqual(['getStaticData']);
const bundleContent = fs.readFileSync(path.join(__dirname, `../../examples/${example}/build/js/main.js`), 'utf-8');
expect(bundleContent.includes('__REMOVED__')).toBe(false);
expect(bundleContent.includes('__LOG__')).toBe(false);
expect(bundleContent.includes('__WARN__')).toBe(false);
expect(bundleContent.includes('__ERROR__')).toBe(true);
expect(bundleContent.includes('__IS_WEB__')).toBe(true);
expect(bundleContent.includes('__IS_NODE__')).toBe(false);
expect(fs.existsSync(path.join(__dirname, `../../examples/${example}/build/favicon.ico`))).toBe(true);
expect(fs.existsSync(path.join(__dirname, `../../examples/${example}/build/js/data-loader.js`))).toBe(true);
const jsonContent = fs.readFileSync(path.join(__dirname, `../../examples/${example}/build/assets-manifest.json`), 'utf-8');
expect(JSON.parse(jsonContent).pages.about.includes('js/framework.js')).toBeFalsy();
const dataLoaderPath = path.join(__dirname, `../../examples/${example}/build/js/data-loader.js`);
// should not contain react
const dataLoaderContent = fs.readFileSync(dataLoaderPath, 'utf-8');
expect(dataLoaderContent.includes('createElement')).toBe(false);
// size of data loader should be less than 14kib
const stats = fs.statSync(dataLoaderPath);
expect(stats.size).toBeLessThan(1024 * 14);
});
test('ClientOnly Component', async () => {
await page.push('/client-only.html');
expect(await page.$$text('#mounted')).toStrictEqual(['Server']);
expect(await page.$$text('#page-url')).toStrictEqual([]);
});
test('disable splitChunks', async () => {
await buildFixture(example, {
config: 'splitChunks.config.mts',
});
const res = await setupBrowser({ example });
page = res.page;
browser = res.browser;
const files = fs.readdirSync(path.join(__dirname, `../../examples/${example}/build/js`), 'utf-8');
expect(files.length).toBe(11);
});
test('render route config when downgrade to CSR.', async () => {
await page.push('/downgrade.html');
expect(await page.$$text('title')).toStrictEqual(['hello']);
expect((await page.$$text('h2')).length).toEqual(0);
});
afterAll(async () => {
await browser.close();
});
});
describe(`start ${example}`, () => {
let page: Page;
let browser: Browser;
const rootDir = path.join(__dirname, `../../examples/${example}`);
test('setup devServer', async () => {
const { devServer, port } = await startFixture(example, {
mock: true,
force: true,
https: false,
analyzer: false,
open: false,
mode: 'start',
});
const res = await setupStartBrowser({ server: devServer, port });
page = res.page;
browser = res.browser;
expect(await page.$$text('h2')).toStrictEqual(['Home Page']);
expect(await page.$$text('#data-from')).toStrictEqual(['getServerData']);
});
test('update route', async () => {
const targetPath = path.join(rootDir, 'src/pages/blog.tsx');
const routeContent = fs.readFileSync(targetPath, 'utf-8');
const routeManifest = fs.readFileSync(path.join(rootDir, '.ice/route-manifest.json'), 'utf-8');
fs.writeFileSync(targetPath, routeContent);
await page.reload();
expect(JSON.parse(routeManifest)[0].children.length).toBe(5);
});
test('update watched file: global.css', () => {
const targetPath = path.join(rootDir, 'src/global.css');
const cssContent = fs.readFileSync(targetPath, 'utf-8');
// Trigger modification of global style
fs.writeFileSync(targetPath, cssContent);
});
test('update watched file: app.ts', () => {
const targetPath = path.join(rootDir, 'src/app.tsx');
const appContent = fs.readFileSync(targetPath, 'utf-8');
// Trigger modification of app entry
fs.writeFileSync(targetPath, appContent);
});
test('should update config during client routing', async () => {
expect(
await page.title(),
).toBe('Home');
expect(
await page.$$attr('meta[name="theme-color"]', 'content'),
).toStrictEqual(['#000']);
await page.push('/about');
await page.waitForNetworkIdle();
expect(
await page.title(),
).toBe('About');
expect(
await page.$$attr('meta[name="theme-color"]', 'content'),
).toStrictEqual(['#eee']);
expect(
await page.$$eval('link[href*="bootstrap"]', (els) => els.length),
).toBe(1);
expect(
await page.$$eval('script[src*="lodash"]', (els) => els.length),
).toBe(1);
});
test('ClientOnly Component', async () => {
await page.push('/client-only');
await page.waitForNetworkIdle();
expect(await page.$$text('#mounted')).toStrictEqual(['Client']);
const pageUrlText = await page.$$text('#page-url');
expect((pageUrlText as string[])[0].endsWith('/client-only')).toBeTruthy();
});
afterAll(async () => {
await browser.close();
});
});
|
9,856 | 0 | petrpan-code/alibaba/ice/tests | petrpan-code/alibaba/ice/tests/integration/disable-data-loader.test.ts | import * as path from 'path';
import * as fs from 'fs';
import { expect, test, describe } from 'vitest';
import { buildFixture } from '../utils/build';
const example = 'disable-data-loader';
describe(`build ${example}`, () => {
test('open /', async () => {
await buildFixture(example);
expect(fs.existsSync(path.join(__dirname, `../../examples/${example}/build/js/data-loader.js`))).toBe(false);
});
}); |
9,857 | 0 | petrpan-code/alibaba/ice/tests | petrpan-code/alibaba/ice/tests/integration/hash-router.test.ts | import { expect, test, describe, afterAll } from 'vitest';
import { buildFixture, setupBrowser } from '../utils/build';
import { startFixture, setupStartBrowser } from '../utils/start';
import type Browser from '../utils/browser';
import type { Page } from '../utils/browser';
const example = 'hash-router';
describe(`build ${example}`, () => {
let page: Page;
let browser: Browser;
test('open /', async () => {
await buildFixture(example);
const res = await setupBrowser({ example, disableJS: false });
page = res.page as Page;
browser = res.browser;
await page.waitForFunction('document.getElementsByTagName(\'h1\').length > 0');
await page.waitForFunction('document.getElementsByTagName(\'h2\').length > 0');
expect(await page.$$text('h1')).toStrictEqual(['Layout']);
expect(await page.$$text('h2')).toStrictEqual(['Home']);
});
afterAll(async () => {
await browser.close();
});
});
describe(`start ${example}`, () => {
let page: Page;
test('open /', async () => {
const { devServer, port } = await startFixture(example);
const res = await setupStartBrowser({ server: devServer, port });
page = res.page;
await page.waitForFunction('document.getElementsByTagName(\'h1\').length > 0');
await page.waitForFunction('document.getElementsByTagName(\'h2\').length > 0');
expect(await page.$$text('h1')).toStrictEqual(['Layout']);
expect(await page.$$text('h2')).toStrictEqual(['Home']);
});
});
|
9,858 | 0 | petrpan-code/alibaba/ice/tests | petrpan-code/alibaba/ice/tests/integration/icestark-child.test.ts | import { test, describe } from 'vitest';
import { buildFixture, setupBrowser } from '../utils/build';
import { startFixture, setupStartBrowser } from '../utils/start';
const example = 'icestark-child';
describe(`build ${example}`, () => {
test('open /', async () => {
await buildFixture(example);
const { page } = await setupBrowser({ example, disableJS: false });
// Test umd output.
await page.waitForFunction('!!window["@examples/icestarkchild"] === true');
});
});
describe(`start ${example}`, () => {
test('setup devServer', async () => {
const { devServer, port } = await startFixture(example);
const { page } = await setupStartBrowser({ server: devServer, port });
// Test umd output.
await page.waitForFunction('!!window["@examples/icestarkchild"] === true');
});
});
|
9,859 | 0 | petrpan-code/alibaba/ice/tests | petrpan-code/alibaba/ice/tests/integration/icestark-layout.test.ts | import { expect, test, describe, afterAll } from 'vitest';
import { startFixture, setupStartBrowser } from '../utils/start';
import type { Page } from '../utils/browser';
import type Browser from '../utils/browser';
const example = 'icestark-layout';
describe(`start ${example}`, () => {
let page: Page;
let browser: Browser;
test('setup devServer', async () => {
const { devServer, port } = await startFixture(example);
const res = await setupStartBrowser({ server: devServer, port });
page = res.page;
browser = res.browser;
});
test('open /seller', async () => {
await page.push('/seller');
await page.waitForFunction('document.getElementsByTagName(\'h3\').length > 0');
expect(await page.$$text('h3')).toStrictEqual(['商家平台']);
});
test('open /waiter', async () => {
await page.push('/waiter');
await page.waitForFunction('document.getElementsByTagName(\'h1\').length > 0');
expect(await page.$$text('h1')).toStrictEqual(['Hello Vite + icestark + Vue3!']);
});
test('open /', async () => {
await page.push('/');
await page.waitForFunction('document.getElementsByTagName(\'h2\').length > 0');
expect(await page.$$text('h2')).toStrictEqual(['Home Page']);
});
afterAll(async () => {
await browser.close();
});
});
|
9,860 | 0 | petrpan-code/alibaba/ice/tests | petrpan-code/alibaba/ice/tests/integration/memory-router.test.ts | import * as path from 'path';
import * as fs from 'fs';
import { expect, test, describe, afterAll } from 'vitest';
import { buildFixture, setupBrowser } from '../utils/build';
import type Browser from '../utils/browser';
const example = 'memory-router';
describe(`build ${example}`, () => {
let browser: Browser;
test('memory router', async () => {
await buildFixture(example);
const outputDir = path.join(__dirname, `../../examples/${example}`, 'build');
fs.writeFileSync(path.join(outputDir, 'test.html'), `
<!DOCTYPE html>
<html>
<body>
<div id="ice-container"></div>
<script src="/js/p_about.js"></script><script src="/js/main.js"></script>
</body>
</html>
`);
const res = await setupBrowser({ example, disableJS: false });
const { page } = res;
browser = res.browser;
await page.push('/test.html');
expect(await page.$$text('h2')).toStrictEqual(['About: 0']);
});
afterAll(async () => {
await browser.close();
});
});
|
9,861 | 0 | petrpan-code/alibaba/ice/tests | petrpan-code/alibaba/ice/tests/integration/miniapp-project.test.ts | import path from 'path';
import { expect, test, describe, afterAll } from 'vitest';
import * as fse from 'fs-extra';
import { buildFixture } from '../utils/build';
const example = 'miniapp-project';
const outputDir = path.join(__dirname, `../../examples/${example}`, 'build', 'wechat');
describe(`build ${example}`, () => {
test('build miniapp assets', async () => {
await buildFixture(example, {
target: 'wechat-miniprogram',
});
});
});
describe(`check ${example} assets`, () => {
test('app.js existence', async () => {
const appJsPath = path.join(outputDir, 'app.js');
const appJsExists = await fse.pathExists(appJsPath);
expect(appJsExists).toStrictEqual(true);
});
test('project.config.json existence', async () => {
const projectConfigPath = path.join(outputDir, 'project.config.json');
const projectConfigExists = await fse.pathExists(projectConfigPath);
expect(projectConfigExists).toStrictEqual(true);
});
afterAll(async () => {
fse.removeSync(outputDir);
});
});
|
9,862 | 0 | petrpan-code/alibaba/ice/tests | petrpan-code/alibaba/ice/tests/integration/multi-target.test.ts | import { expect, test, describe, afterAll } from 'vitest';
import { buildFixture, setupBrowser } from '../utils/build';
import { startFixture, setupStartBrowser } from '../utils/start';
import type { Page } from '../utils/browser';
const example = 'multi-target';
describe(`build ${example}`, () => {
let page: Page = null;
let browser = null;
test('open /about', async () => {
await buildFixture(example);
const res = await setupBrowser({ example, defaultHtml: 'about.html' });
page = res.page;
browser = res.browser;
// Compare text.
expect((await page.$$text('#about'))[0]).contains('Target=web Renderer=server');
});
afterAll(async () => {
await browser.close();
});
});
describe(`start ${example}`, () => {
let page: Page = null;
let browser = null;
test('setup devServer', async () => {
const { devServer, port } = await startFixture(example);
const res = await setupStartBrowser({ server: devServer, port, defaultPath: '/about' });
page = res.page;
browser = res.browser;
expect((await page.$$text('#about'))[0]).contains('Target=web Renderer=client');
});
afterAll(async () => {
await browser.close();
});
});
|
9,863 | 0 | petrpan-code/alibaba/ice/tests | petrpan-code/alibaba/ice/tests/integration/rax-inline-style.test.ts | import { expect, test, describe, afterAll } from 'vitest';
import { buildFixture, setupBrowser } from '../utils/build';
import { startFixture, setupStartBrowser } from '../utils/start';
import type { Page } from '../utils/browser';
import type Browser from '../utils/browser';
const example = 'rax-inline-style';
describe(`build ${example}`, () => {
let page: Page;
let browser: Browser;
test('open /', async () => {
await buildFixture(example);
const res = await setupBrowser({ example });
page = res.page;
browser = res.browser;
// css module
expect((await page.$$attr('img', 'class'))[0]).contain('logo');
// css module
expect((await page.$$attr('span', 'class'))[0]).contain('title');
// inline css from node_modules
expect((await page.$$attr('span', 'style'))[0]).contain('display:block');
// inline index.css
expect((await page.$$attr('span', 'style'))[1]).contain('color:rgb(85,85,85)');
});
afterAll(async () => {
await browser.close();
});
});
describe(`start ${example}`, () => {
let page: Page;
let browser: Browser;
test('setup devServer', async () => {
const { devServer, port } = await startFixture(example);
const res = await setupStartBrowser({ server: devServer, port });
page = res.page;
browser = res.browser;
await page.waitForFunction("document.getElementsByTagName('span').length > 0");
// css module
expect((await page.$$attr('img', 'class'))[0]).contain('logo');
// css module
expect((await page.$$attr('span', 'class'))[0]).contain('title');
// inline css from node_modules
expect((await page.$$attr('span', 'style'))[0]).contain('display:block');
// inline index.css
expect((await page.$$attr('span', 'style'))[1]).contain('color:rgb(85,85,85)');
});
afterAll(async () => {
await browser.close();
});
});
|
9,864 | 0 | petrpan-code/alibaba/ice/tests | petrpan-code/alibaba/ice/tests/integration/rax-project.test.ts | import * as path from 'path';
import * as fs from 'fs';
import { expect, test, describe, afterAll } from 'vitest';
import { buildFixture, setupBrowser } from '../utils/build';
import { startFixture, setupStartBrowser } from '../utils/start';
import type { Page } from '../utils/browser';
const example = 'rax-project';
describe(`build ${example}`, () => {
let page: Page = null;
let browser = null;
test('open /', async () => {
await buildFixture(example);
const res = await setupBrowser({ example });
page = res.page;
browser = res.browser;
expect((await page.$$text('span')).length).toEqual(3);
expect((await page.$$text('span'))[0]).toStrictEqual('Welcome to Your Rax App');
expect((await page.$$text('span'))[1]).toStrictEqual('More information about Rax');
expect((await page.$$text('span'))[2]).toStrictEqual('Visit https://rax.js.org');
expect((await page.$$text('img')).length).toEqual(1);
expect(fs.existsSync(path.join(__dirname, `../../examples/${example}/build/js/data-loader.js`))).toBe(false);
});
afterAll(async () => {
await browser.close();
});
});
describe(`start ${example}`, () => {
let page: Page = null;
let browser = null;
test('setup devServer', async () => {
const { devServer, port } = await startFixture(example);
const res = await setupStartBrowser({ server: devServer, port });
page = res.page;
browser = res.browser;
await page.waitForFunction('document.getElementsByTagName(\'span\').length > 0');
expect((await page.$$text('span')).length).toEqual(3);
expect((await page.$$text('span'))[0]).toStrictEqual('Welcome to Your Rax App');
expect((await page.$$text('span'))[1]).toStrictEqual('More information about Rax');
expect((await page.$$text('span'))[2]).toStrictEqual('Visit https://rax.js.org');
expect((await page.$$text('img')).length).toEqual(1);
});
afterAll(async () => {
await browser.close();
});
});
|
9,865 | 0 | petrpan-code/alibaba/ice/tests | petrpan-code/alibaba/ice/tests/integration/routes-config.test.ts | import { expect, test, describe, afterAll } from 'vitest';
import { startFixture, setupStartBrowser } from '../utils/start';
import type { Page } from '../utils/browser';
import type Browser from '../utils/browser';
const example = 'routes-config';
describe(`start ${example}`, () => {
let page: Page;
let browser: Browser;
test('open /', async () => {
const { devServer, port } = await startFixture(example);
const res = await setupStartBrowser({ server: devServer, port });
page = res.page;
browser = res.browser;
expect(await page.$$text('a')).toStrictEqual(['link to sales page']);
});
test('rewrite link', async () => {
await page.push('/rewrite/overview');
expect(await page.$$text('h2')).toStrictEqual(['overview all sale items']);
});
afterAll(async () => {
await browser.close();
});
});
|
Subsets and Splits