'React ui-router test state change
I need to write a test using Jest and enzyme that covers the basic implementation of react/ui-router in my application. All it needs to do is assert that a component is loaded in the DOM after a programatic state transition occurs.
I've been digging around in the docs and here on SO but can't find a way to accomplish this.
I have a simple state setup for a Home component
export const states = [
{
url: '/home',
name: 'home',
component: Home,
}
];
This is the test that I'm trying to accomplish:
import React from 'react';
import { Transition } from '@uirouter/react';
import { mount } from 'enzyme';
import { Home, Page } from './components/Layout';
describe('UIRouter', () => {
it('go to home state', () => {
Transition.router.stateService.go('home');
const wrapper = mount(
<UIRouter router={router} >
<Page /> //component that contains <UIView />
</UIRouter>\
);
expect(wrapper.find(<Home />).length).toBe(1);
});
});
When I try this code, I get the error:
TypeError: Cannot read property 'stateService' of undefined
package.json:
@uirouter/react": "^0.8.0",
"react": "^16.3.2",
"react-dom": "^16.3.2",
"react-scripts": "1.1.4"
"enzyme": "^3.3.0",
Any insight is appreciated!
Solution 1:[1]
I think you need to use the router not Transition. Does this work?
import React from 'react';
import { Transition, UIRouterReact } from '@uirouter/react';
import { mount } from 'enzyme';
import { Home, Page } from './components/Layout';
import { states } from './states';
describe('UIRouter', () => {
it('go to home state', () => {
const router = new UIRouterReact();
router.stateService.go('home');
const wrapper = mount(
<UIRouter router={router} states={states}>
<Page /> //component that contains <UIView />
</UIRouter>\
);
expect(wrapper.find(<Home />).length).toBe(1);
});
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Marcellino Ornelas |
