enzyme#render TypeScript Examples
The following examples show how to use
enzyme#render.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: responses.tsx From ask-sdk-jsx-for-apl with Apache License 2.0 | 6 votes |
describe('responses', () => {
describe('alexa-layouts', () => {
test('imports work with APL', () => {
UserAgentManager.registerComponent = jest.fn();
render(
<>
<APL>
<MainTemplate>
<Container width="100%">
<Container width="50%">
<Text color="black" text={`You said ?`} />
</Container>
<AlexaLists listItems={[]} />
</Container>
</MainTemplate>
</APL>
</>
);
expect(responseBuilder.addDirective).toHaveBeenCalledTimes(1);
expect(UserAgentManager.registerComponent).toHaveBeenCalledTimes(1);
expect(UserAgentManager.registerComponent).toHaveBeenCalledWith(expect.stringContaining('ask-sdk-jsx-for-apl'));
expect(getImportDefinition()).toEqual({
"name": "alexa-layouts",
"version": "1.1.0"
});
});
});
});
Example #2
Source File: TableContainer.test.tsx From grafana-chinese with Apache License 2.0 | 6 votes |
describe('TableContainer', () => {
it('should render component', () => {
const props = {
exploreId: ExploreId.left as ExploreId,
loading: false,
width: 800,
onClickCell: jest.fn(),
showingTable: true,
tableResult: {} as DataFrame,
toggleTable: {} as typeof toggleTable,
};
const wrapper = shallow(<TableContainer {...props} />);
expect(wrapper).toMatchSnapshot();
});
it('should render 0 series returned on no items', () => {
const props = {
exploreId: ExploreId.left as ExploreId,
loading: false,
width: 800,
onClickCell: jest.fn(),
showingTable: true,
tableResult: {
name: 'TableResultName',
fields: [],
length: 0,
} as DataFrame,
toggleTable: {} as typeof toggleTable,
};
const wrapper = render(<TableContainer {...props} />);
expect(wrapper.find('0 series returned')).toBeTruthy();
});
});
Example #3
Source File: MetaInfoText.test.tsx From grafana-chinese with Apache License 2.0 | 6 votes |
describe('MetaInfoText', () => {
it('should render component', () => {
const items: MetaItemProps[] = [
{ label: 'label', value: 'value' },
{ label: 'label2', value: 'value2' },
];
const wrapper = shallow(<MetaInfoText metaItems={items} />);
expect(wrapper).toMatchSnapshot();
});
it('should render items', () => {
const items: MetaItemProps[] = [
{ label: 'label', value: 'value' },
{ label: 'label2', value: 'value2' },
];
const wrapper = render(<MetaInfoText metaItems={items} />);
expect(wrapper.find('label')).toBeTruthy();
expect(wrapper.find('value')).toBeTruthy();
expect(wrapper.find('label2')).toBeTruthy();
expect(wrapper.find('value2')).toBeTruthy();
});
it('should render no items when the array is empty', () => {
const items: MetaItemProps[] = [];
const wrapper = shallow(<MetaInfoText metaItems={items} />);
expect(wrapper.find('div').exists()).toBeTruthy();
expect(wrapper.find('div').children()).toHaveLength(0);
});
});
Example #4
Source File: CallToActionCard.test.tsx From grafana-chinese with Apache License 2.0 | 6 votes |
describe('CallToActionCard', () => {
describe('rendering', () => {
it('when no message and footer provided', () => {
const tree = render(<TestRenderer callToActionElement={<a href="http://dummy.link">Click me</a>} />);
expect(tree).toMatchSnapshot();
});
it('when message and no footer provided', () => {
const tree = render(
<TestRenderer message="Click button bellow" callToActionElement={<a href="http://dummy.link">Click me</a>} />
);
expect(tree).toMatchSnapshot();
});
it('when message and footer provided', () => {
const tree = render(
<TestRenderer
message="Click button bellow"
footer="footer content"
callToActionElement={<a href="http://dummy.link">Click me</a>}
/>
);
expect(tree).toMatchSnapshot();
});
});
});
Example #5
Source File: index.test.tsx From geist-ui with MIT License | 6 votes |
describe(' User', () => {
it('should render correctly', () => {
const wrapper = mount(<User name="witt" />)
expect(() => wrapper.unmount()).not.toThrow()
})
it('should support image and text', () => {
const wrapper = render(
<div>
<User name="witt" text="witt" />
<User name="witt" src="https://unix.bio/assets/avatar.png" />
</div>,
)
expect(wrapper).toMatchSnapshot()
})
it('should render description correctly', () => {
const wrapper = mount(<User name="witt">description</User>)
expect(wrapper.text().toLowerCase()).toContain('description')
})
it('should render link on user.link', () => {
const wrapper = mount(
<User name="witt">
<User.Link href="https://twitter.com/echo_witt">twitter</User.Link>
</User>,
)
const link = wrapper.find('a')
expect(link.length).not.toBe(0)
})
it('should pass alt attribute', () => {
const wrapper = mount(
<User name="witt" src="https://unix.bio/assets/avatar.png" altText="witt" />,
)
expect(wrapper.find('img').prop('alt')).toEqual('witt')
})
})
Example #6
Source File: index.test.tsx From geist-ui with MIT License | 6 votes |
describe('Tag', () => {
it('should render correctly', () => {
const wrapper = mount(<Tag>tag</Tag>)
expect(() => wrapper.unmount()).not.toThrow()
})
it('should work with types', () => {
const wrapper = render(
<div>
<Tag type="success">success</Tag>
<Tag type="secondary">secondary</Tag>
<Tag type="error">error</Tag>
<Tag type="dark">dark</Tag>
</div>,
)
expect(wrapper).toMatchSnapshot()
})
it('should work with invert', () => {
const wrapper = render(
<Tag type="success" invert>
success
</Tag>,
)
expect(wrapper).toMatchSnapshot()
})
it('should work when child is null', () => {
const wrapper = mount(<Tag />)
expect(() => wrapper.unmount()).not.toThrow()
})
})
Example #7
Source File: index.test.tsx From geist-ui with MIT License | 6 votes |
describe('Dot', () => {
it('should render correctly', () => {
const wrapper = mount(<Dot />)
expect(wrapper).toMatchSnapshot()
expect(() => wrapper.unmount()).not.toThrow()
})
it('should supports types', () => {
const wrapper = render(
<div>
<Dot type="success" />
<Dot type="secondary" />
<Dot type="warning" />
<Dot type="error" />
</div>,
)
expect(wrapper).toMatchSnapshot()
})
it('should be render text', () => {
const wrapper = mount(<Dot>test</Dot>)
expect(wrapper.text()).toContain('test')
})
})
Example #8
Source File: index.test.tsx From geist-ui with MIT License | 6 votes |
describe('Display', () => {
it('should render correctly', () => {
const wrapper = mount(<Display caption="caption">display</Display>)
expect(wrapper).toMatchSnapshot()
expect(() => wrapper.unmount()).not.toThrow()
})
it('should support react-node', () => {
const wrapper = mount(<Display caption={<h1>h1</h1>}>display</Display>)
expect(wrapper).toMatchSnapshot()
expect(wrapper.find('h1').length).not.toBe(0)
})
it('should work with shadow and width', () => {
const wrapper = render(
<div>
<Display caption={<h1>h1</h1>} shadow>
display
</Display>
<Display caption={<h1>h1</h1>} width="50px">
display
</Display>
</div>,
)
expect(wrapper).toMatchSnapshot()
})
})
Example #9
Source File: baseline.test.tsx From geist-ui with MIT License | 6 votes |
describe('CSSBaseline', () => {
it('should render correctly', () => {
const wrapper = render(
<GeistProvider>
<CssBaseline />
</GeistProvider>,
)
expect(wrapper).toMatchSnapshot()
})
it('should render dark mode correctly', () => {
const wrapper = render(
<GeistProvider themeType="dark">
<CssBaseline />
</GeistProvider>,
)
expect(wrapper).toMatchSnapshot()
})
})
Example #10
Source File: index.test.tsx From geist-ui with MIT License | 6 votes |
describe('Code', () => {
it('should render correctly', () => {
const wrapper = mount(<Code>code</Code>)
expect(() => wrapper.unmount()).not.toThrow()
})
it('should support block mode', () => {
const wrapper = render(<Code block>code</Code>)
expect(wrapper).toMatchSnapshot()
})
it('should repspond to changed by width', () => {
const wrapper = render(
<Code block width="50%">
code
</Code>,
)
expect(wrapper).toMatchSnapshot()
})
it('should render pre element only in block mode', () => {
const wrapper = mount(<Code>code</Code>)
expect(wrapper.find('pre').length).toBe(0)
wrapper.setProps({ block: true })
expect(wrapper.find('pre').length).not.toBe(0)
})
it('should work correctly with title', () => {
const wrapper = render(
<Code block name="name" classic>
code
</Code>,
)
expect(wrapper).toMatchSnapshot()
})
})
Example #11
Source File: index.test.tsx From geist-ui with MIT License | 6 votes |
describe('Capacity', () => {
it('should render value correctly', () => {
const wrapper = mount(<Capacity value={50} />)
expect(() => wrapper.unmount()).not.toThrow()
})
it('should render title correctly', () => {
const wrapper = mount(<Capacity value={50} />)
const el = wrapper.find('.capacity').first()
const title = el.getDOMNode().getAttribute('title')
expect(title).toEqual('50%')
})
it('should render different widths based on limit-value', () => {
const wrapper = render(
<div>
<Capacity value={20} />
<Capacity value={20} limit={50} />
<Capacity value={20} limit={30} />
</div>,
)
expect(wrapper).toMatchSnapshot()
})
it('should override background color', () => {
const capacity = render(<Capacity value={50} color="white" />)
expect(capacity).toMatchSnapshot()
})
})
Example #12
Source File: index.test.tsx From geist-ui with MIT License | 5 votes |
describe('Badge', () => {
it('should supoort text', () => {
const html = render(<Badge>count</Badge>)
expect(html).toMatchSnapshot()
const badge = mount(<Badge>count</Badge>)
expect(() => badge.unmount()).not.toThrow()
})
it('should support baisc sizes', () => {
const mini = shallow(<Badge scale={2}>mini</Badge>)
expect(() => mini.unmount()).not.toThrow()
const small = shallow(<Badge scale={5}>small</Badge>)
expect(() => small.unmount()).not.toThrow()
const medium = shallow(<Badge scale={10}>medium</Badge>)
expect(() => medium.unmount()).not.toThrow()
const large = shallow(<Badge margin="20px">large</Badge>)
expect(() => large.unmount()).not.toThrow()
})
it('should re-render when size changed', () => {
const badge = mount(<Badge>size</Badge>)
badge.setProps({ size: 'small' })
expect(badge).toMatchSnapshot()
badge.setProps({ size: 'mini' })
expect(badge).toMatchSnapshot()
})
it('should render different types', () => {
const wrapper = render(
<div>
<Badge type="success">badge</Badge>
<Badge type="secondary">badge</Badge>
<Badge type="warning">badge</Badge>
<Badge type="error">badge</Badge>
</div>,
)
expect(wrapper).toMatchSnapshot()
})
it('should overwrite style by inline-style', () => {
const badge = mount(
<Badge style={{ background: 'white' }} type="success">
badge
</Badge>,
)
const span = badge.find('span')
expect(span).not.toBeUndefined()
expect(span.props().style).not.toBeUndefined()
expect((span.props().style as any).background).toBe('white')
})
it('should hide content when in dot mode', () => {
const wrapper = mount(<Badge dot>test-value</Badge>)
expect(wrapper.html()).not.toContain('test-value')
expect(() => wrapper.unmount()).not.toThrow()
})
})
Example #13
Source File: responses.tsx From ask-sdk-jsx-for-apl with Apache License 2.0 | 5 votes |
renderAndGet = (apl: React.ReactElement): RenderDocumentDirective => {
render(apl);
return (responseBuilder.addDirective as Mock<unknown>).mock.calls[0][0].document;
}
Example #14
Source File: form.spec.tsx From react-bare-forms with MIT License | 5 votes |
describe("<Form />", () => {
it("should render form tags with no other elements", () => {
act(() => {
ReactDOM.render(<MockComponent />, container);
});
expect(container.querySelector("form").childElementCount).toBe(0);
});
xit("should contain a context object with state and form props", () => {
let myState = {
username: "joebloggs"
};
let context = {state: myState};
function MockComponent() {
const [state, setState] = React.useState(myState);
return (<Form state={state} context={setState}></Form>);
}
let testFormRederer: any = TestRenderer.create(
<MockComponent />
);
const testFormInstance = testFormRederer.root;
expect(testFormInstance.props).toEqual(context);
});
it("should render a form element with no extra tags", () => {
let state = {
username: "joebloggs"
};
const tree = TestRenderer.create(
<MockComponent state={state} />
).toJSON();
expect(tree).toMatchSnapshot();
function MockComponentTwo() {
const [_state, setState] = React.useState(state);
return (
<MockComponent state={state} bare={"true"}>
<TextInputField
name="username"
value={_state.username}
/>
</MockComponent>);
}
const wrapper = render(<MockComponentTwo />);
expect(wrapper.find(".form-group")).toHaveLength(0);
expect(wrapper.find(".form-control")).toHaveLength(0);
});
xit("should render a form element with bootstrap extra tags", () => {
let state = {
username: "joebloggs"
};
const tree: any = TestRenderer.create(<MockComponent state={state} />);
expect(tree.toJSON()).toMatchSnapshot();
const wrapper = render(<MockComponent state={state} />);
expect(wrapper.find(".form-group")).toHaveLength(1);
expect(wrapper.find(".form-control")).toHaveLength(1);
});
});
Example #15
Source File: index.test.tsx From geist-ui with MIT License | 5 votes |
describe('Avatar', () => {
it('should support square and circle', () => {
const circle = shallow(<Avatar />)
expect(() => circle.unmount()).not.toThrow()
const square = shallow(<Avatar isSquare />)
expect(() => square.unmount()).not.toThrow()
})
it('should render text element', () => {
const imageAvatar = render(<Avatar />)
expect(imageAvatar).toMatchSnapshot()
const textAvatar = render(<Avatar text="text" />)
expect(textAvatar).toMatchSnapshot()
})
it('should omit long chars automatically', () => {
const avatar = mount(<Avatar text="texttexttexttext" />)
const text = avatar.find('.avatar-text').text()
expect(text.length).toBeLessThan(4)
})
it('stacked should be work', () => {
const avatar = shallow(<Avatar src="/images/avatar.png" stacked />)
expect(() => avatar.unmount()).not.toThrow()
})
it('group component should render all children', () => {
const group = mount(
<Avatar.Group>
<Avatar />
<Avatar />
</Avatar.Group>,
)
expect(group.find('.avatar')).toHaveLength(2)
})
it('should stacked when avatars are in a group', () => {
const group = render(
<Avatar.Group>
<Avatar />
<Avatar />
</Avatar.Group>,
)
expect(group).toMatchSnapshot()
})
it('should show count in group', () => {
const count = 20
const group = render(<Avatar.Group count={count} />)
const text = group.find('.count').text()
expect(text).toMatch(`${count}`)
})
})
Example #16
Source File: browser.test.tsx From geist-ui with MIT License | 5 votes |
describe('Image Browser', () => {
it('should render correctly', () => {
const wrapper = mount(
<Image.Browser url={link}>
<Image src={url} />
</Image.Browser>,
)
expect(() => wrapper.unmount()).not.toThrow()
const browser = render(
<Image.Browser url={link}>
<Image src={url} />
</Image.Browser>,
)
expect(browser).toMatchSnapshot()
})
it('show title when url missing', () => {
const wrapper = mount(
<Image.Browser title="test-title">
<Image src={url} />
</Image.Browser>,
)
expect(wrapper.find('header').text()).toContain('test-title')
})
it('should work correctly with full link', () => {
const wrapper = mount(
<Image.Browser url={link}>
<Image src={url} />
</Image.Browser>,
)
expect(wrapper.find('.link').text()).not.toContain('http')
wrapper.setProps({ showFullLink: true })
expect(wrapper.find('.link').text()).toContain('http')
})
it('show full link when url parse error', () => {
const errorLink = 'httpsw/com'
const wrapper = mount(
<Image.Browser url={errorLink}>
<Image src={url} />
</Image.Browser>,
)
expect(wrapper.find('.link').text()).toContain(errorLink)
})
it('should work correctly when props missing', () => {
const wrapper = mount(<Image.Browser />)
expect(() => wrapper.unmount()).not.toThrow()
})
it('anchor props should be passed through', () => {
const anchorRel = 'noreferrer'
const wrapper = mount(
<Image.Browser url={link} anchorProps={{ rel: anchorRel }}>
<Image src={url} />
</Image.Browser>,
)
const rel = wrapper.find('a').getDOMNode().getAttribute('rel')
expect(rel).toEqual(anchorRel)
})
})
Example #17
Source File: index.test.tsx From geist-ui with MIT License | 5 votes |
describe('Fieldset', () => {
it('should mount correctly', () => {
const wrapper = mount(
<Fieldset>
<Fieldset.Title>title</Fieldset.Title>
<Fieldset.Subtitle>subtitle</Fieldset.Subtitle>
<Fieldset.Footer>
status
<button>Actions</button>
</Fieldset.Footer>
</Fieldset>,
)
expect(() => wrapper.unmount()).not.toThrow()
})
it('should render correctly', () => {
const wrapper = render(
<Fieldset>
<Fieldset.Title>title</Fieldset.Title>
<Fieldset.Subtitle>subtitle</Fieldset.Subtitle>
<Fieldset.Footer>
status
<button>Actions</button>
</Fieldset.Footer>
</Fieldset>,
)
expect(wrapper).toMatchSnapshot()
})
it('the component Fieldset.Content should be injected automatically', () => {
const fieldset = mount(
<Fieldset>
<Fieldset.Title>test-title</Fieldset.Title>
<Fieldset.Subtitle>test-subtitle</Fieldset.Subtitle>
</Fieldset>,
)
const content = mount(
<Fieldset>
<Fieldset.Content>
<Fieldset.Title>test-title</Fieldset.Title>
<Fieldset.Subtitle>test-subtitle</Fieldset.Subtitle>
</Fieldset.Content>
</Fieldset>,
)
expect(fieldset.html()).toEqual(content.html())
expect(() => content.unmount()).not.toThrow()
})
it('render children through props', () => {
const fieldset = mount(
<Fieldset>
<Fieldset.Title>test-title</Fieldset.Title>
<Fieldset.Subtitle>test-subtitle</Fieldset.Subtitle>
</Fieldset>,
)
const props = mount(<Fieldset title="test-title" subtitle="test-subtitle" />)
expect(fieldset.html()).toEqual(props.html())
expect(() => props.unmount()).not.toThrow()
})
})
Example #18
Source File: index.test.tsx From geist-ui with MIT License | 5 votes |
describe('Divider', () => {
it('should render correctly', () => {
const wrapper = mount(<Divider />)
expect(wrapper).toMatchSnapshot()
expect(() => wrapper.unmount()).not.toThrow()
})
it('should work with w and h', () => {
const wrapper = render(
<div>
<Divider w={3} />
<Divider h={3} />
</div>,
)
expect(wrapper).toMatchSnapshot()
})
it('should work with type', () => {
const wrapper = render(
<div>
<Divider type="secondary" />
<Divider type="warning" />
<Divider type="dark" />
</div>,
)
expect(wrapper).toMatchSnapshot()
})
it('should work with align and volume', () => {
const wrapper = render(
<div>
<Divider align="start">start</Divider>
<Divider align="left">left</Divider>
<Divider align="end">end</Divider>
<Divider align="start" h={2}>
start
</Divider>
</div>,
)
expect(wrapper).toMatchSnapshot()
})
it('should support float', () => {
const wrapper = mount(
<div>
<Divider w={1.1} h={2.5} />
<Divider h={2.5} />
</div>,
)
expect(wrapper).toMatchSnapshot()
expect(() => wrapper.unmount()).not.toThrow()
})
})
Example #19
Source File: index.test.tsx From geist-ui with MIT License | 5 votes |
describe('Collapse', () => {
it('should render correctly', () => {
const wrapper = mount(<Collapse title="title">content</Collapse>)
expect(wrapper).toMatchSnapshot()
expect(() => wrapper.unmount()).not.toThrow()
})
it('should work with subtitle and shadow', () => {
const wrapper = render(
<div>
<Collapse title="title" subtitle="subtitle">
content
</Collapse>
<Collapse title="title" subtitle="subtitle" shadow>
content
</Collapse>
</div>,
)
expect(wrapper).toMatchSnapshot()
})
it('should work with initial visible', () => {
const wrapper = render(
<div>
<Collapse title="title" subtitle="subtitle">
content
</Collapse>
<Collapse title="title" initialVisible>
content
</Collapse>
</div>,
)
expect(wrapper).toMatchSnapshot()
})
it('should throw error when title missing', () => {
const Component = Collapse as any
let errorMessage = ''
const errorSpy = jest
.spyOn(console, 'error')
.mockImplementation(msg => (errorMessage = msg))
mount(<Component subtitle="subtitle">content</Component>)
expect(errorMessage.toLowerCase()).not.toEqual('')
errorSpy.mockRestore()
})
it('should expand when title clicked', async () => {
const wrapper = mount(<Collapse title="title">content</Collapse>)
wrapper.find('.view').at(0).simulate('click')
await updateWrapper(wrapper, 300)
expect(wrapper.find('.expanded').length).not.toBe(0)
})
})
Example #20
Source File: group.test.tsx From geist-ui with MIT License | 5 votes |
describe('Collapse Group', () => {
it('should render correctly', () => {
const wrapper = mount(
<Collapse.Group>
<Collapse title="title1">content1</Collapse>
<Collapse title="title2">content2</Collapse>
</Collapse.Group>,
)
expect(wrapper).toMatchSnapshot()
expect(() => wrapper.unmount()).not.toThrow()
})
it('should be no errors when children are missing', () => {
const wrapper = mount(<Collapse.Group></Collapse.Group>)
expect(wrapper).toMatchSnapshot()
expect(() => wrapper.unmount()).not.toThrow()
})
it('should work without accordion', () => {
const wrapper = render(
<Collapse.Group accordion={false}>
<Collapse title="title1">content1</Collapse>
<Collapse title="title2">content2</Collapse>
</Collapse.Group>,
)
expect(wrapper).toMatchSnapshot()
})
it('should be display all when without accordion', async () => {
const wrapper = mount(
<Collapse.Group accordion={false}>
<Collapse title="title1">content1</Collapse>
<Collapse title="title2">content2</Collapse>
</Collapse.Group>,
)
const views = wrapper.find('.view')
views.at(0).simulate('click')
views.at(1).simulate('click')
await updateWrapper(wrapper, 300)
expect(wrapper.find('.expanded').length).toBe(2)
views.at(0).simulate('click')
views.at(1).simulate('click')
await updateWrapper(wrapper, 300)
expect(wrapper.find('.expanded').length).toBe(0)
})
it('should be display one when in accordion mode', async () => {
const wrapper = mount(
<Collapse.Group>
<Collapse title="title1">content1</Collapse>
<Collapse title="title2">content2</Collapse>
</Collapse.Group>,
)
const views = wrapper.find('.view')
views.at(0).simulate('click')
views.at(1).simulate('click')
await updateWrapper(wrapper, 300)
expect(wrapper.find('.expanded').length).toBe(1)
views.at(1).simulate('click')
await updateWrapper(wrapper, 300)
expect(wrapper.find('.expanded').length).toBe(0)
})
})
Example #21
Source File: index.test.tsx From geist-ui with MIT License | 5 votes |
describe('Col', () => {
it('should render correctly', () => {
const wrapper = mount(<Col>col</Col>)
expect(wrapper).toMatchSnapshot()
expect(() => wrapper.unmount()).not.toThrow()
})
it('should work with span and offset', () => {
const wrapper = render(
<div>
<Col span={2}>col</Col>
<Col span={2} offset={2}>
col
</Col>
</div>,
)
expect(wrapper).toMatchSnapshot()
})
it('should render correctly when nested', () => {
const wrapper = mount(
<Col>
<Col>
<Col />
col
</Col>
</Col>,
)
expect(() => wrapper.unmount()).not.toThrow()
})
it('should render different components', () => {
let wrapper = mount(<Col component="p" />)
expect(wrapper.find('p').length).not.toBe(0)
wrapper = mount(<Col component="details" />)
expect(wrapper.find('details').length).not.toBe(0)
wrapper = mount(<Col component="h1" />)
expect(wrapper.find('h1').length).not.toBe(0)
})
})
Example #22
Source File: index.test.tsx From geist-ui with MIT License | 5 votes |
describe('Card', () => {
it('should render correctly', () => {
const wrapper = mount(<Card>card</Card>)
expect(() => wrapper.unmount()).not.toThrow()
})
it('should support shadow and hoverable', () => {
const wrapper = render(
<div>
<Card hoverable>card</Card>
<Card shadow>card</Card>
<Card shadow hoverable>
card
</Card>
</div>,
)
expect(wrapper).toMatchSnapshot()
})
it('should support card types', () => {
const wrapper = mount(
<div>
<Card type="secondary">card</Card>
<Card type="success">card</Card>
<Card type="violet">card</Card>
<Card type="lite">card</Card>
<Card type="cyan">card</Card>
<Card type="secondary">card</Card>
<Card type="warning">card</Card>
</div>,
)
expect(() => wrapper.unmount()).not.toThrow()
})
it('should render correctly when nested', () => {
const wrapper = render(
<Card>
<Card shadow>
<Card>card</Card>
</Card>
</Card>,
)
expect(wrapper).toMatchSnapshot()
})
it('the component Card.Content should be injected automatically', () => {
const card = mount(<Card>test-value</Card>)
const content = mount(
<Card>
<Card.Content>test-value</Card.Content>
</Card>,
)
expect(card.html()).toEqual(content.html())
})
})
Example #23
Source File: index.test.tsx From geist-ui with MIT License | 5 votes |
describe('Checkbox', () => {
it('should render correctly', () => {
const wrapper = mount(<Checkbox checked={true}>Sydney</Checkbox>)
expect(() => wrapper.unmount()).not.toThrow()
const rendered = render(<Checkbox>Sydney</Checkbox>)
expect(rendered).toMatchSnapshot()
})
it('should work with different status', () => {
const wrapper = mount(
<div>
<Checkbox type="secondary" />
<Checkbox type="success" />
<Checkbox type="warning" />
<Checkbox type="error" />
</div>,
)
expect(wrapper.html()).toMatchSnapshot()
})
it('should work correctly with initial value', () => {
let wrapper = mount(<Checkbox checked={true}>Sydney</Checkbox>)
let input = wrapper.find('input').getDOMNode()
expect((input as HTMLInputElement).checked).toBeTruthy()
wrapper = mount(<Checkbox checked={false}>Sydney</Checkbox>)
input = wrapper.find('input').getDOMNode()
expect((input as HTMLInputElement).checked).not.toBeTruthy()
wrapper = mount(<Checkbox initialChecked>Sydney</Checkbox>)
input = wrapper.find('input').getDOMNode()
expect((input as HTMLInputElement).checked).toBeTruthy()
wrapper = mount(<Checkbox initialChecked={false}>Sydney</Checkbox>)
input = wrapper.find('input').getDOMNode()
expect((input as HTMLInputElement).checked).not.toBeTruthy()
})
it('should change value after click', () => {
const Wrapper = () => {
const [state, setState] = React.useState<string>('state1')
return (
<Checkbox initialChecked onChange={() => setState('state2')}>
{state}
</Checkbox>
)
}
const wrapper = mount(<Wrapper />)
const input = wrapper.find('input').at(0)
input.simulate('change')
expect(wrapper.find('.text').text()).toContain('state2')
})
it('should ignore events when disabled', () => {
const Wrapper = () => {
const [state, setState] = React.useState<string>('state1')
return (
<Checkbox disabled onChange={() => setState('state2')}>
{state}
</Checkbox>
)
}
const wrapper = mount(<Wrapper />)
const input = wrapper.find('input').at(0)
input.simulate('change')
expect(wrapper.find('.text').text()).not.toContain('state2')
})
})
Example #24
Source File: index.test.tsx From geist-ui with MIT License | 4 votes |
describe('Button Dropdown', () => {
it('should render correctly', () => {
const wrapper = mount(
<ButtonDropdown>
<ButtonDropdown.Item main>Default Action</ButtonDropdown.Item>
<ButtonDropdown.Item>Secondary Action</ButtonDropdown.Item>
<ButtonDropdown.Item>Tertiary Action</ButtonDropdown.Item>
</ButtonDropdown>,
)
expect(() => wrapper.unmount()).not.toThrow()
})
it('right icon should render correctly', () => {
const wrapper = mount(
<ButtonDropdown icon={<Icon />}>
<ButtonDropdown.Item main>Default Action</ButtonDropdown.Item>
<ButtonDropdown.Item>Secondary Action</ButtonDropdown.Item>
<ButtonDropdown.Item>Tertiary Action</ButtonDropdown.Item>
</ButtonDropdown>,
)
expect(() => wrapper.unmount()).not.toThrow()
})
it('should support types', () => {
const wrapper = render(
<div>
<ButtonDropdown auto>
<ButtonDropdown.Item main>Auto Mini</ButtonDropdown.Item>
</ButtonDropdown>
<ButtonDropdown>
<ButtonDropdown.Item main>Auto Mini</ButtonDropdown.Item>
</ButtonDropdown>
<ButtonDropdown type="secondary">
<ButtonDropdown.Item main>Secondary Action</ButtonDropdown.Item>
</ButtonDropdown>
</div>,
)
expect(wrapper).toMatchSnapshot()
})
it('should trigger callback function', () => {
const Wrapper = () => {
const [state, setState] = React.useState<string>('state1')
return (
<ButtonDropdown type="secondary">
<ButtonDropdown.Item main onClick={() => setState('state2')}>
{state}
</ButtonDropdown.Item>
</ButtonDropdown>
)
}
const wrapper = mount(<Wrapper />)
expect(wrapper.text()).toContain('state1')
wrapper.find('button').simulate('click', nativeEvent)
expect(wrapper.text()).toContain('state2')
})
it('should work correctly when callback missing', () => {
const wrapper = mount(
<ButtonDropdown type="secondary">
<ButtonDropdown.Item main></ButtonDropdown.Item>
</ButtonDropdown>,
)
wrapper.find('button').simulate('click', nativeEvent)
expect(() => wrapper.unmount()).not.toThrow()
})
it('should ignore all events when loading', () => {
const Wrapper = () => {
const [state, setState] = React.useState<string>('state1')
return (
<ButtonDropdown type="secondary" loading>
<ButtonDropdown.Item main onClick={() => setState('state2')}>
{state}
</ButtonDropdown.Item>
</ButtonDropdown>
)
}
const wrapper = mount(<Wrapper />)
wrapper.find('button').simulate('click', nativeEvent)
expect(wrapper.text()).not.toContain('state2')
})
it('should ignore all events when disabled', () => {
const Wrapper = () => {
const [state, setState] = React.useState<string>('state1')
return (
<ButtonDropdown type="secondary" disabled>
<ButtonDropdown.Item main onClick={() => setState('state2')}>
{state}
</ButtonDropdown.Item>
</ButtonDropdown>
)
}
const wrapper = mount(<Wrapper />)
wrapper.find('summary').simulate('click', nativeEvent)
wrapper.find('button').simulate('click', nativeEvent)
expect(wrapper.text()).not.toContain('state2')
})
it('should render multiple types', () => {
const wrapper = render(
<ButtonDropdown auto>
<ButtonDropdown.Item main type="success">
Auto Mini
</ButtonDropdown.Item>
<ButtonDropdown.Item type="warning">Auto Mini</ButtonDropdown.Item>
<ButtonDropdown.Item type="error">Auto Mini</ButtonDropdown.Item>
</ButtonDropdown>,
)
expect(wrapper).toMatchSnapshot()
})
it('should expand after click', () => {
const wrapper = mount(
<ButtonDropdown>
<ButtonDropdown.Item main>Default Action</ButtonDropdown.Item>
<ButtonDropdown.Item>Secondary Action</ButtonDropdown.Item>
<ButtonDropdown.Item>Tertiary Action</ButtonDropdown.Item>
</ButtonDropdown>,
)
wrapper.find('summary').simulate('click', nativeEvent)
const open = wrapper.find('details').prop('open')
expect(open).toBeTruthy()
})
it('should stop propagation', () => {
let stopped = false
const nativeEvent = mockNativeEvent(() => (stopped = true))
const wrapper = mount(
<ButtonDropdown>
<ButtonDropdown.Item main>Default Action</ButtonDropdown.Item>
<ButtonDropdown.Item>Secondary Action</ButtonDropdown.Item>
<ButtonDropdown.Item>Tertiary Action</ButtonDropdown.Item>
</ButtonDropdown>,
)
wrapper.find('summary').simulate('click', nativeEvent)
expect(stopped).toBeTruthy()
})
})
Example #25
Source File: group.test.tsx From geist-ui with MIT License | 4 votes |
describe('Checkbox Group', () => {
it('should render correctly', () => {
const wrapper = mount(
<Checkbox.Group value={[]}>
<Checkbox value="sydney">Sydney</Checkbox>
</Checkbox.Group>,
)
expect(() => wrapper.unmount()).not.toThrow()
const rendered = render(
<Checkbox.Group value={[]}>
<Checkbox value="sydney">Sydney</Checkbox>
</Checkbox.Group>,
)
expect(rendered).toMatchSnapshot()
})
it('should work correctly with initial value', () => {
let wrapper = mount(
<Checkbox.Group value={['sydney']}>
<Checkbox value="sydney">Sydney</Checkbox>
<Checkbox value="beijing">BeiJing</Checkbox>
</Checkbox.Group>,
)
const sydney = wrapper.find('input').at(0).getDOMNode()
expect((sydney as HTMLInputElement).checked).toBeTruthy()
const beijing = wrapper.find('input').at(1).getDOMNode()
expect((beijing as HTMLInputElement).checked).not.toBeTruthy()
})
it('should change value after click', () => {
let value = ['sydney']
const wrapper = mount(
<Checkbox.Group value={['sydney']} onChange={val => (value = val)}>
<Checkbox value="sydney">Sydney</Checkbox>
<Checkbox value="beijing">BeiJing</Checkbox>
</Checkbox.Group>,
)
const sydney = wrapper.find('input').at(0)
sydney.simulate('change')
expect(value.length).toBe(0)
const beijing = wrapper.find('input').at(1)
beijing.simulate('change')
expect(value).toEqual(expect.arrayContaining(['beijing']))
})
it('should ignore events when disabled', () => {
let value = ['sydney']
const wrapper = mount(
<Checkbox.Group disabled value={['sydney']} onChange={val => (value = val)}>
<Checkbox value="sydney">Sydney</Checkbox>
<Checkbox value="beijing">BeiJing</Checkbox>
</Checkbox.Group>,
)
const sydney = wrapper.find('input').at(0)
sydney.simulate('change')
expect(value.length).not.toBe(0)
const beijing = wrapper.find('input').at(1)
beijing.simulate('change')
expect(value).not.toEqual(expect.arrayContaining(['beijing']))
})
it('should throw error when value missing', () => {
let errorMessage = ''
const Group = Checkbox.Group as any
const errorSpy = jest
.spyOn(console, 'error')
.mockImplementation(msg => (errorMessage = msg))
mount(
<Group>
<Checkbox value="sydney">Sydney</Checkbox>
<Checkbox value="beijing">BeiJing</Checkbox>
</Group>,
)
expect(errorMessage).toContain('required')
errorSpy.mockRestore()
})
it('should throw error when set check prop in group', () => {
let errorMessage = ''
const errorSpy = jest
.spyOn(console, 'error')
.mockImplementation(msg => (errorMessage = msg))
mount(
<Checkbox.Group value={[]}>
<Checkbox value="sydney" checked>
Sydney
</Checkbox>
<Checkbox value="beijing">BeiJing</Checkbox>
</Checkbox.Group>,
)
expect(errorMessage.toLowerCase()).toContain('remove props')
errorSpy.mockRestore()
})
})
Example #26
Source File: index.test.tsx From geist-ui with MIT License | 4 votes |
describe('Select', () => {
it('should render correctly', () => {
const wrapper = mount(
<div>
<Select />
<Select scale={2} />
</div>,
)
expect(wrapper.html()).toMatchSnapshot()
expect(() => wrapper.unmount()).not.toThrow()
})
it('should work with different status', () => {
const wrapper = mount(
<div>
<Select type="secondary" />
<Select type="success" />
<Select type="warning" />
<Select type="error" />
</div>,
)
expect(wrapper.html()).toMatchSnapshot()
})
it('should work correctly with labels', () => {
const wrapper = mount(
<Select>
<Select.Option label>1</Select.Option>
<Select.Option divider>1</Select.Option>
<Select.Option divider label>
1
</Select.Option>
<Select.Option value="1">1</Select.Option>
<Select.Option value="2">Option 2</Select.Option>
</Select>,
)
expect(wrapper.html()).toMatchSnapshot()
expect(() => wrapper.unmount()).not.toThrow()
})
it('should work with different icons', () => {
const MockIcon = () => <span>icon</span>
const pure = render(<Select pure />)
expect(pure).toMatchSnapshot()
const icon = render(<Select icon={MockIcon} />)
expect(icon).toMatchSnapshot()
})
it('should render value with initial-value', () => {
const wrapper = mount(
<Select initialValue="2">
<Select.Option value="1">1</Select.Option>
<Select.Option value="2">Option 2</Select.Option>
</Select>,
)
expect(wrapper.find('.value').text()).toContain('Option 2')
})
it('should trigger events when option changed', async () => {
let value = ''
const changeHandler = jest.fn().mockImplementation(val => (value = val))
const wrapper = mount(
<Select onChange={changeHandler}>
<Select.Option value="1">1</Select.Option>
<Select.Option value="2">Option 2</Select.Option>
</Select>,
)
wrapper.find('.select').simulate('click', nativeEvent)
wrapper.find('.select-dropdown').find('.option').at(0).simulate('click', nativeEvent)
await updateWrapper(wrapper, 350)
expect(changeHandler).toHaveBeenCalled()
expect(value).toEqual('1')
changeHandler.mockRestore()
})
it('should ignore events when disabled', async () => {
const changeHandler = jest.fn()
const wrapper = mount(
<Select onChange={changeHandler} disabled>
<Select.Option value="1">1</Select.Option>
<Select.Option value="2">Option 2</Select.Option>
</Select>,
)
wrapper.find('.select').simulate('click', nativeEvent)
expect(wrapper.find('.select-dropdown').length).toBe(0)
changeHandler.mockRestore()
})
it('should ignore option when option disabled', async () => {
let value = ''
const changeHandler = jest.fn().mockImplementation(val => (value = val))
const wrapper = mount(
<Select onChange={changeHandler}>
<Select.Option value="1">1</Select.Option>
<Select.Option value="2" disabled>
Option 2
</Select.Option>
</Select>,
)
wrapper.find('.select').simulate('click', nativeEvent)
wrapper.find('.select-dropdown').find('.option').at(1).simulate('click', nativeEvent)
await updateWrapper(wrapper, 350)
expect(changeHandler).not.toHaveBeenCalled()
expect(value).not.toEqual('2')
changeHandler.mockRestore()
})
it('should ignore option when prevent all', async () => {
let value = ''
const changeHandler = jest.fn().mockImplementation(val => (value = val))
const wrapper = mount(
<Select onChange={changeHandler}>
<Select.Option value="1">1</Select.Option>
<Select.Option value="2" preventAllEvents>
Option 2
</Select.Option>
</Select>,
)
wrapper.find('.select').simulate('click', nativeEvent)
wrapper.find('.select-dropdown').find('.option').at(1).simulate('click', nativeEvent)
await updateWrapper(wrapper, 350)
expect(changeHandler).not.toHaveBeenCalled()
expect(value).not.toEqual('2')
changeHandler.mockRestore()
})
it('should be change when value changed', async () => {
const wrapper = mount(
<Select>
<Select.Option value="1">Option 1</Select.Option>
<Select.Option value="2">Option 2</Select.Option>
</Select>,
)
wrapper.setProps({ value: '2' })
await updateWrapper(wrapper, 300)
expect(wrapper.find('.value').text()).toContain('Option 2')
wrapper.setProps({ value: '1' })
await updateWrapper(wrapper, 300)
expect(wrapper.find('.value').text()).toContain('Option 1')
})
it('should be wraning when ident value missing', () => {
let errorMessage = ''
const errorSpy = jest
.spyOn(console, 'error')
.mockImplementation(msg => (errorMessage = msg))
const SelectOption = Select.Option as any
const wrapper = mount(
<Select>
<SelectOption>1</SelectOption>
</Select>,
)
wrapper.find('.select').simulate('click', nativeEvent)
expect(errorMessage).toContain('required')
errorSpy.mockRestore()
})
})
Example #27
Source File: search.test.tsx From geist-ui with MIT License | 4 votes |
describe('AutoComplete Search', () => {
it('should render options element', () => {
const wrapper = mount(<AutoComplete options={mockOptions} />)
wrapper.find('input').at(0).simulate('focus')
let dropdown = wrapper.find('.auto-complete-dropdown').children()
expect(dropdown.length).not.toBe(0)
wrapper.find('input').at(0).simulate('blur')
expect(() => wrapper.unmount()).not.toThrow()
})
it('should update value when dropdown clicked', () => {
let value = ''
const wrapper = mount(
<AutoComplete options={mockOptions} onChange={val => (value = val)} />,
)
wrapper.find('input').at(0).simulate('focus')
wrapper.find('.item').at(0).simulate('click', nativeEvent)
expect(value).toEqual('london')
})
it('should ignore events when disabled', () => {
let value = ''
const wrapper = mount(
<AutoComplete disabled options={mockOptions} onChange={val => (value = val)} />,
)
wrapper.find('input').at(0).simulate('focus')
wrapper.find('.item').at(0).simulate('click', nativeEvent)
expect(value).not.toEqual('london')
})
it('should render searching component', async () => {
let wrapper = mount(<AutoComplete searching={false} options={mockOptions} />)
await act(async () => {
wrapper.setProps({ searching: true })
})
wrapper.find('input').at(0).simulate('focus')
let dropdown = wrapper.find('.auto-complete-dropdown')
expect(dropdown.text()).not.toContain('london')
const loading = wrapper.find('.loading')
expect(loading.length).not.toBe(0)
wrapper = mount(
<AutoComplete searching options={mockOptions}>
<AutoComplete.Searching>
<span>waiting...</span>
</AutoComplete.Searching>
</AutoComplete>,
)
wrapper.find('input').at(0).simulate('focus')
dropdown = wrapper.find('.auto-complete-dropdown')
expect(dropdown.text()).toContain('waiting')
})
it('should hide empty component', () => {
let wrapper = render(
<AutoComplete placeholder="Enter here">
<AutoComplete.Empty hidden />
</AutoComplete>,
)
expect(wrapper).toMatchSnapshot()
wrapper = render(
<AutoComplete placeholder="Enter here">
<AutoComplete.Empty>empty</AutoComplete.Empty>
</AutoComplete>,
)
expect(wrapper).toMatchSnapshot()
const mountWrapper = mount(
<AutoComplete placeholder="Enter here" initialValue="value">
<AutoComplete.Empty>empty</AutoComplete.Empty>
</AutoComplete>,
)
mountWrapper.find('input').at(0).simulate('focus')
const text = mountWrapper.find('.auto-complete-dropdown').text()
expect(text).toContain('empty')
const mountWrapper2 = mount(
<AutoComplete placeholder="Enter here" initialValue="value">
<AutoComplete.Empty hidden>empty</AutoComplete.Empty>
</AutoComplete>,
)
mountWrapper2.find('input').at(0).simulate('focus')
const text2 = mountWrapper2.find('.auto-complete-dropdown').text()
expect(text2).not.toContain('empty')
})
it('should trigger search handler', () => {
const handler = jest.fn()
const wrapper = mount(<AutoComplete initialValue="value" onSearch={handler} />)
const input = wrapper.find('input').at(0)
input.simulate('focus')
input.simulate('change')
;(input.getDOMNode() as HTMLInputElement).value = 'value'
expect(handler).toHaveBeenCalled()
})
it('should trigger select and change handler', () => {
const selectHandler = jest.fn()
const changeHandler = jest.fn()
const wrapper = mount(
<AutoComplete
options={mockOptions}
initialValue="value"
onSelect={selectHandler}
onChange={changeHandler}
/>,
)
wrapper.find('input').at(0).simulate('focus')
wrapper.find('.item').at(0).simulate('click', nativeEvent)
expect(selectHandler).toHaveBeenCalled()
expect(changeHandler).toHaveBeenCalled()
})
it('should work with custom options', () => {
const changeHandler = jest.fn()
const makeOption = (label: string, value: string): any => (
<AutoComplete.Option value={value}>
<span>{label}</span>
</AutoComplete.Option>
)
const options = mockOptions.map(
({ label, value }) => makeOption(label, value) as typeof AutoComplete.Option,
)
const wrapper = mount(<AutoComplete options={options} onChange={changeHandler} />)
wrapper.find('input').at(0).simulate('focus')
wrapper.find('.item').at(0).simulate('click', nativeEvent)
expect(changeHandler).toHaveBeenCalled()
})
it('should work correctly without options', () => {
const wrapper = mount(<AutoComplete options={[]} />)
expect(() => wrapper.unmount()).not.toThrow()
})
it('value should be reset when freeSolo disabled', async () => {
const wrapper = mount(<AutoComplete initialValue="value" disableFreeSolo />)
const input = wrapper.find('input').at(0)
input.simulate('focus')
input.simulate('change', { target: { value: 'test' } })
expect((input.getDOMNode() as HTMLInputElement).value).toEqual('test')
input.simulate('blur')
await updateWrapper(wrapper, 200)
expect((input.getDOMNode() as HTMLInputElement).value).toEqual('value')
})
})
Example #28
Source File: test.tsx From react-resource-router with Apache License 2.0 | 4 votes |
describe('SPA Router store', () => {
const { location } = window;
beforeAll(() => {
delete window.location;
// @ts-ignore
window.location = {};
Object.defineProperties(window.location, {
href: { value: location.href },
assign: { value: jest.fn() },
replace: { value: jest.fn() },
});
});
afterEach(() => {
defaultRegistry.stores.clear();
jest.resetAllMocks();
jest.restoreAllMocks();
});
afterAll(() => {
window.location = location;
});
describe('initialising the store', () => {
beforeEach(() => {
jest
.spyOn(historyHelper, 'createMemoryHistory')
// @ts-ignore
.mockImplementation(() => mockHistory);
});
it('should call the history listener when initialised', () => {
mount(
<MemoryRouter routes={[]}>
<RouterSubscriber>
{() => <div>I am a subscriber</div>}
</RouterSubscriber>
</MemoryRouter>
);
expect(mockHistory.listen).toBeCalled();
});
it('should send right props after render with routes', () => {
mount(
<MemoryRouter routes={[mockRoutes[0]]}>
<RouterSubscriber>
{({
history,
location: currentLocation,
routes,
route,
match,
query,
}) => {
expect(history).toEqual(mockHistory);
expect(currentLocation).toEqual(mockLocation);
expect(routes).toEqual(routes);
expect(route).toEqual(
expect.objectContaining({
path: `/pathname`,
})
);
expect(match).toBeTruthy();
expect(query).toEqual({
foo: 'bar',
});
return <div>I am a subscriber</div>;
}}
</RouterSubscriber>
</MemoryRouter>
);
});
it('should use default store values if no overrides are provided', () => {
expect.assertions(1);
render(
<RouterSubscriber>
{renderProps => {
expect(renderProps).toEqual(
expect.objectContaining({
...INITIAL_STATE,
history: expect.objectContaining({
push: expect.any(Function),
replace: expect.any(Function),
goBack: expect.any(Function),
goForward: expect.any(Function),
listen: expect.any(Function),
block: expect.any(Function),
createHref: expect.any(Function),
}),
})
);
return <div>I am a lonely subscriber</div>;
}}
</RouterSubscriber>
);
});
});
describe('listening for real history changes on history@4', () => {
let children: any;
beforeEach(() => {
children = jest.fn().mockReturnValue(null);
});
it('should send location with route change', async () => {
mount(
<MemoryRouter routes={mockRoutes} location={mockRoutes[0].path}>
<RouterSubscriber>{children}</RouterSubscriber>
</MemoryRouter>
);
const { history } = children.mock.calls[0][0];
await nextTick();
expect(children.mock.calls[0]).toEqual([
expect.objectContaining({
routes: mockRoutes,
route: mockRoutes[0],
action: DEFAULT_ACTION,
history: expect.any(Object),
}),
expect.any(Object),
]);
const newLocation = {
pathname: '/blah',
search: '?somequery=value',
hash: '#bing',
};
history.push(Object.values(newLocation).join(''));
await nextTick();
expect(children.mock.calls[1]).toEqual([
expect.objectContaining({
routes: mockRoutes,
route: mockRoutes[1],
action: 'PUSH',
history: expect.any(Object),
}),
expect.any(Object),
]);
});
it('should send correct action key for route changes', async () => {
mount(
<MemoryRouter routes={mockRoutes}>
<RouterSubscriber>{children}</RouterSubscriber>
</MemoryRouter>
);
const { history } = children.mock.calls[0][0];
expect(children.mock.calls[0]).toEqual([
expect.objectContaining({
action: DEFAULT_ACTION,
}),
expect.any(Object),
]);
history.push('/pathname');
await nextTick();
expect(children.mock.calls[1]).toEqual([
expect.objectContaining({
action: 'PUSH',
}),
expect.any(Object),
]);
history.replace('/blah');
await nextTick();
expect(children.mock.calls[2]).toEqual([
expect.objectContaining({
action: 'REPLACE',
}),
expect.any(Object),
]);
});
});
describe('listening for real history changes on history@5', () => {
let children: any;
beforeEach(() => {
children = jest.fn().mockReturnValue(null);
jest
.spyOn(historyHelper, 'createMemoryHistory')
// @ts-ignore
.mockImplementation(historyHelper5.createMemoryHistory);
});
it('should send location with route change', async () => {
mount(
<MemoryRouter routes={mockRoutes} location={mockRoutes[0].path}>
<RouterSubscriber>{children}</RouterSubscriber>
</MemoryRouter>
);
const { history } = children.mock.calls[0][0];
await nextTick();
expect(children.mock.calls[0]).toEqual([
expect.objectContaining({
routes: mockRoutes,
route: mockRoutes[0],
action: DEFAULT_ACTION,
history: expect.any(Object),
}),
expect.any(Object),
]);
const newLocation = {
pathname: '/blah',
search: '?somequery=value',
hash: '#bing',
};
history.push(Object.values(newLocation).join(''));
await nextTick();
expect(children.mock.calls[1]).toEqual([
expect.objectContaining({
routes: mockRoutes,
route: mockRoutes[1],
action: 'PUSH',
history: expect.any(Object),
}),
expect.any(Object),
]);
});
it('should send correct action key for route changes', async () => {
mount(
<MemoryRouter routes={mockRoutes}>
<RouterSubscriber>{children}</RouterSubscriber>
</MemoryRouter>
);
const { history } = children.mock.calls[0][0];
expect(children.mock.calls[0]).toEqual([
expect.objectContaining({
action: DEFAULT_ACTION,
}),
expect.any(Object),
]);
history.push('/pathname');
await nextTick();
expect(children.mock.calls[1]).toEqual([
expect.objectContaining({
action: 'PUSH',
}),
expect.any(Object),
]);
history.replace('/blah');
await nextTick();
expect(children.mock.calls[2]).toEqual([
expect.objectContaining({
action: 'REPLACE',
}),
expect.any(Object),
]);
});
});
describe('store actions', () => {
const currentLocation = 'http://localhost/';
beforeEach(() => {
jest
.spyOn(historyHelper, 'createMemoryHistory')
// @ts-ignore
.mockImplementation(() => mockHistory);
});
describe('push', () => {
let children: any;
beforeEach(() => {
children = jest.fn().mockReturnValue(null);
});
it('should push a relative path if the URL is absolute but on the same domain', () => {
mount(
<MemoryRouter routes={[]}>
<RouterSubscriber>{children}</RouterSubscriber>
</MemoryRouter>
);
const path = 'http://localhost:3000/board/123';
const { actions } = getRouterStore();
actions.push(path);
// expect(window.location.href).toEqual(currentLocation);
expect(mockHistory.push).toBeCalledWith('/board/123');
});
it('should call window.location.assign with the absolute URL if it is on a different domain', () => {
jest
.spyOn(window.location, 'assign')
.mockImplementation(() => jest.fn());
mount(
<MemoryRouter routes={[]}>
<RouterSubscriber>{children}</RouterSubscriber>
</MemoryRouter>
);
const path = 'http://example.com';
const { actions } = getRouterStore();
actions.push(path);
expect(window.location.href).toEqual(currentLocation);
expect(window.location.assign).toBeCalledWith(path);
});
});
describe('pushTo', () => {
let children: any;
beforeEach(() => {
children = jest.fn().mockReturnValue(null);
});
it('should push a relative path generated from route and parameters', () => {
mount(
<MemoryRouter routes={[]}>
<RouterSubscriber>{children}</RouterSubscriber>
</MemoryRouter>
);
const route = { name: '', path: '/page/:id', component: () => null };
const { actions } = getRouterStore();
actions.pushTo(route, { params: { id: '1' }, query: { uid: '1' } });
expect(mockHistory.push).toBeCalledWith({
hash: '',
pathname: '/page/1',
search: '?uid=1',
});
});
});
describe('replace', () => {
let children: any;
beforeEach(() => {
children = jest.fn().mockReturnValue(null);
});
it('should replace a relative path if the URL is absolute but on the same domain', () => {
mount(
<MemoryRouter routes={[]}>
<RouterSubscriber>{children}</RouterSubscriber>
</MemoryRouter>
);
const path = 'http://localhost:3000/board/123';
const { actions } = getRouterStore();
actions.replace(path);
expect(window.location.href).toEqual(currentLocation);
expect(mockHistory.replace).toBeCalledWith('/board/123');
});
it('should call window.location.replace with the absolute URL if it is on a different domain', () => {
jest
.spyOn(window.location, 'replace')
.mockImplementation(() => jest.fn());
mount(
<MemoryRouter routes={[]}>
<RouterSubscriber>{children}</RouterSubscriber>
</MemoryRouter>
);
const path = 'http://example.com';
const { actions } = getRouterStore();
actions.replace(path);
expect(window.location.href).toEqual(currentLocation);
expect(window.location.replace).toBeCalledWith(path);
});
});
describe('replaceTo', () => {
let children: any;
beforeEach(() => {
children = jest.fn().mockReturnValue(null);
});
it('should replace a relative path generated from route and parameters', () => {
mount(
<MemoryRouter routes={[]}>
<RouterSubscriber>{children}</RouterSubscriber>
</MemoryRouter>
);
const route = { name: '', path: '/page/:id', component: () => null };
const { actions } = getRouterStore();
actions.replaceTo(route, { params: { id: '1' }, query: { uid: '1' } });
expect(mockHistory.replace).toBeCalledWith({
hash: '',
pathname: '/page/1',
search: '?uid=1',
});
});
});
});
describe('resource store interop', () => {
const containerProps = {
isStatic: false,
history: mockHistory,
routes: [],
resourceContext: {},
resourceData: {},
};
let children: any;
beforeEach(() => {
jest.clearAllMocks();
children = jest.fn().mockReturnValue(null);
});
it('should hydrate the resource store state when bootstrapped', () => {
const resourceContext = { foo: 'bar' };
const resourceData = {};
const initialResourceStoreState = {
resourceContext,
resourceData,
};
const props = { ...containerProps, ...initialResourceStoreState };
const spy = jest.spyOn(getResourceStore().actions, 'hydrate');
// @ts-ignore - mocks
getRouterStore().actions.bootstrapStore(props);
expect(spy).toBeCalledWith({
resourceContext,
resourceData,
});
});
it('should request route resources when the router is mounted', () => {
const spy = jest.spyOn(getResourceStore().actions, 'requestAllResources');
mount(
<MemoryRouter routes={mockRoutes}>
<RouterSubscriber>{children}</RouterSubscriber>
</MemoryRouter>
);
const { route, match, query } = getRouterState();
expect(spy).toBeCalledTimes(1);
expect(spy).toBeCalledWith(
{
route,
match,
query,
},
{
timeout: undefined,
}
);
});
});
describe('history listen resource store interop', () => {
const getResourceStoreStateData = () =>
getResourceStore().storeState.getState().data;
const componentRenderSpy = jest.fn();
let componentRenderStates: string[] = [];
beforeEach(() => {
componentRenderSpy.mockImplementation(arg =>
componentRenderStates.push(arg)
);
});
afterEach(() => {
defaultRegistry.stores.clear();
componentRenderStates = [];
});
const mountAppSetInitialLocationAndGetHistoryPush = async (
routes: any[],
initialLocation: string
): Promise<any> => {
let historyPush = (path: string) => {
path;
};
mount(
<MemoryRouter routes={routes} location={initialLocation}>
<RouterSubscriber>
{(
{ route, location: currentLocation, query, match, action },
{ push }
) => {
historyPush = push;
return !route ? null : (
<route.component
route={route}
location={currentLocation}
query={query}
match={match}
action={action}
/>
);
}}
</RouterSubscriber>
</MemoryRouter>
);
await nextTick();
return historyPush;
};
const resourceA = createResource({
type: 'TYPE_A',
getKey: () => 'KEY_A',
getData: () => Promise.resolve(`A-${Date.now()}`),
maxAge: 0,
});
const resourceB = createResource({
type: 'TYPE_B',
getKey: () => 'KEY_B',
getData: () => Promise.resolve(`B-${Date.now()}`),
maxAge: Infinity,
});
it('should transition between routes and not render components with stale data', async () => {
const ComponentA = () => (
<ResourceSubscriber resource={resourceA}>
{({ data, loading }) => {
if (loading) {
return <div>{componentRenderSpy(`loading:A`)}</div>;
}
return <div>{componentRenderSpy(`data:${String(data)}`)}</div>;
}}
</ResourceSubscriber>
);
const ComponentB = () => (
<ResourceSubscriber resource={resourceB}>
{props => {
if (props.loading) {
return <div>{props.loading}</div>;
}
if (props.error) {
return <div>{props.error}</div>;
}
return <div>{props.data.toString()}</div>;
}}
</ResourceSubscriber>
);
const routes = [
{
...mockRoute,
path: '/foo/a',
component: ComponentA,
resources: [resourceA],
},
{
...mockRoute,
path: '/foo/b',
component: ComponentB,
resources: [resourceB],
},
];
jest.spyOn(global.Date, 'now').mockReturnValue(100);
// We start at route fooA
const historyPush = await mountAppSetInitialLocationAndGetHistoryPush(
routes,
routes[0].path
);
const { data: dataA1 } = getResourceStoreStateData().TYPE_A.KEY_A;
jest.spyOn(global.Date, 'now').mockReturnValue(150);
// We go to route fooB
historyPush(routes[1].path);
await nextTick();
jest.spyOn(global.Date, 'now').mockReturnValue(200);
// We go back to fooA
historyPush(routes[0].path);
await nextTick();
const { data: dataA2 } = getResourceStoreStateData().TYPE_A.KEY_A;
expect(dataA1 === dataA2).toBeFalsy();
expect(componentRenderStates).toEqual([
'loading:A',
`data:${dataA1}`,
'loading:A',
`data:${dataA2}`,
]);
});
it('should always get new data when doing full route changes and resources have expired', async () => {
const ComponentA = () => (
<ResourceSubscriber resource={resourceA}>
{({ data, loading }) => {
if (loading) {
return <div>{componentRenderSpy(`loading:A`)}</div>;
}
let message = '';
if (data === null) {
message = 'isNullAndCleanedByTransitionOutOfA';
} else {
message = String(data);
}
return <div>{componentRenderSpy(`data:${message}`)}</div>;
}}
</ResourceSubscriber>
);
const ComponentB = () => (
<ResourceSubscriber resource={resourceA}>
{({ data, loading }) => {
if (loading) {
return <div>{componentRenderSpy(`loading:B`)}</div>;
}
let message = '';
if (data === null) {
message = 'isNullAndCleanedByTransitionIntoB';
} else {
message = String(data);
}
return <div>{componentRenderSpy(`data:${message}`)}</div>;
}}
</ResourceSubscriber>
);
const routes = [
{
...mockRoute,
path: '/foo/a',
component: ComponentA,
resources: [resourceA, resourceB],
},
{
...mockRoute,
name: 'bar',
path: '/bar/a',
component: ComponentB,
resources: [resourceA, resourceB],
},
];
jest.spyOn(global.Date, 'now').mockReturnValue(100);
// We start at route fooA
const historyPush = await mountAppSetInitialLocationAndGetHistoryPush(
routes,
routes[0].path
);
const { data: dataA1 } = getResourceStoreStateData().TYPE_A.KEY_A;
jest.spyOn(global.Date, 'now').mockReturnValue(150);
// We go to routeB
act(() => historyPush(routes[1].path));
await nextTick();
const { data: dataA2 } = getResourceStoreStateData().TYPE_A.KEY_A;
expect(dataA1 === dataA2).toBeFalsy();
expect(componentRenderStates).toEqual([
'loading:A',
`data:${dataA1}`,
'loading:B',
`data:${dataA2}`,
]);
});
it('should not clean resources when transitioning to the same route and keys have not changed', async () => {
const ComponentA = () => (
<ResourceSubscriber resource={resourceA}>
{({ data, loading }) => {
if (loading) {
return <div>{componentRenderSpy(`loading:A`)}</div>;
}
let message = '';
if (data === null) {
message = 'isNullAndCleanedByTransitionIntoB';
} else {
message = String(data);
}
return <div>{componentRenderSpy(`data:${message}`)}</div>;
}}
</ResourceSubscriber>
);
const routes = [
{
...mockRoute,
path: '/foo/a',
component: ComponentA,
resources: [resourceA],
},
];
jest.spyOn(global.Date, 'now').mockReturnValue(100);
// We start at route fooA
const historyPush = await mountAppSetInitialLocationAndGetHistoryPush(
routes,
routes[0].path
);
const { data: dataA1 } = getResourceStoreStateData().TYPE_A.KEY_A;
jest.spyOn(global.Date, 'now').mockReturnValue(150);
historyPush(`${routes[0].path}?blah`);
await nextTick();
// This means the resource was never cleaned
expect(
componentRenderStates.includes('data:isNullAndCleanedByTransitionIntoB')
).toBeFalsy();
expect(componentRenderStates).toEqual([
'loading:A',
`data:${dataA1}`,
`data:${dataA1}`,
]);
});
it('should not refresh cached resources when transitioning on the same route', async () => {
const ComponentB = () => (
<ResourceSubscriber resource={resourceB}>
{({ data, loading }) => {
if (loading) {
return <div>{componentRenderSpy(`loading:B`)}</div>;
}
let message = '';
if (data === null) {
message = 'isNullAndCleanedByTransitionIntoB';
} else {
message = String(data);
}
return <div>{componentRenderSpy(`data:${message}`)}</div>;
}}
</ResourceSubscriber>
);
const routes = [
{
...mockRoute,
path: '/bar/:key',
component: ComponentB,
resources: [resourceA, resourceB],
},
];
jest.spyOn(global.Date, 'now').mockReturnValue(100);
// We start at route fooA
const historyPush = await mountAppSetInitialLocationAndGetHistoryPush(
routes,
'/bar/first-key'
);
const { data: dataA1 } = getResourceStoreStateData().TYPE_B.KEY_B;
jest.spyOn(global.Date, 'now').mockReturnValue(150);
// We go to routeB
historyPush('/bar/second-key');
await nextTick();
const { data: dataA2 } = getResourceStoreStateData().TYPE_B.KEY_B;
expect(dataA1 === dataA2).toBeTruthy();
expect(componentRenderStates.includes('data:null')).toBeFalsy();
});
});
describe('createRouterSelector', () => {
it('should return selected state', () => {
const mockSelector = jest.fn().mockImplementation(s => s.route.name);
const useRouteName = createRouterSelector(mockSelector);
const RouteName = () => <>{useRouteName()}</>;
const route = { path: '', name: 'home', component: () => null };
const wrapper = mount(
<MemoryRouter routes={[route]}>
<RouteName />
</MemoryRouter>
);
expect(mockSelector).toBeCalledWith(
expect.objectContaining({ route }),
undefined
);
expect(wrapper.html()).toEqual('home');
});
it('should pass through single hook argument to selector', () => {
const mockSelector = jest.fn().mockImplementation(s => s.route.name);
const useRouteName = createRouterSelector(mockSelector);
const RouteName = ({ argument }: { argument: unknown }) => (
<>{useRouteName(argument)}</>
);
const route = { path: '', name: 'home', component: () => null };
const wrapper = mount(
<MemoryRouter routes={[route]}>
<RouteName argument="bar" />
</MemoryRouter>
);
expect(mockSelector).toBeCalledWith(
expect.objectContaining({ route }),
'bar'
);
expect(wrapper.html()).toEqual('home');
});
});
});
Example #29
Source File: test.tsx From react-resource-router with Apache License 2.0 | 4 votes |
describe('Router Actions Component', () => { window.history.replaceState = jest.fn(); window.history.back = jest.fn(); window.history.forward = jest.fn(); const { location } = window; beforeAll(() => { delete window.location; // @ts-ignore window.location = {}; Object.defineProperties(window.location, { assign: { value: jest.fn() }, }); }); afterEach(() => { defaultRegistry.stores.clear(); }); afterAll(() => { window.location = location; }); test('when no history is provided it should fall back to default link actions', () => { let unblockMethod; render( <RouterActions> {({ push, replace, goBack, goForward, registerBlock }) => { push('push'); replace('replace'); goBack(); goForward(); unblockMethod = registerBlock(jest.fn()); return <div>Link Action here</div>; }} </RouterActions> ); expect(window.location.assign).toBeCalledWith('push'); expect(window.history.replaceState).toBeCalledWith({}, '', 'replace'); expect(window.history.back).toBeCalled(); expect(window.history.forward).toBeCalled(); expect(unblockMethod).toEqual(noop); }); test('when history is provided should use history methods', () => { const unblockMethod = jest.fn(); const blockCallback = jest.fn(); let unblocker; HistoryMock.block.mockReturnValue(unblockMethod); render( // @ts-ignore <Router history={HistoryMock} routes={[]}> <RouterActions> {({ push, replace, goBack, goForward, registerBlock }) => { push('push'); replace('replace'); goBack(); goForward(); unblocker = registerBlock(blockCallback); return <div>Link Action here</div>; }} </RouterActions> </Router> ); expect(HistoryMock.push).toBeCalledWith('push'); expect(HistoryMock.replace).toBeCalledWith('replace'); expect(HistoryMock.goBack).toBeCalled(); expect(HistoryMock.goForward).toBeCalled(); expect(HistoryMock.block).toHaveBeenCalledWith(blockCallback); expect(unblocker).toEqual(unblockMethod); }); });