0
所以我從react-router (v4)
創建基於Route
一個RestrictedRoute
成分,並使用從recompose
branch
方法:酶 - 測試限制航線
import React from 'react';
import { connect } from 'react-redux';
import { compose, branch, renderComponent } from 'recompose';
import { Route, Redirect } from 'react-router-dom';
const RestrictedRoute = (props) => {
const { component, ...otherProps } = props;
return <Route {...otherProps} component={component} />;
};
const mapStateToProps = state => ({
authenticated: state.authentication.session,
});
const branched = branch(
({ authenticated }) => !authenticated,
renderComponent(() => <Redirect to="/" />),
);
const enhanced = compose(
connect(mapStateToProps),
branched,
)(RestrictedRoute);
export default enhanced;
這工作完全正常,但現在我需要編寫一些測試來告訴我,如果重定向工作properl,所以我這樣做:
import React from 'react';
import { shallow } from 'enzyme';
import { Provider } from 'react-redux';
import { Redirect, MemoryRouter } from 'react-router-dom';
import configureStore from 'redux-mock-store';
import RestrictedRoute from '../RestrictedRoute';
import { initialAuthenticationState } from 'Reducers/authentication';
describe('<RestrictedRoute />',() => {
const mockStore = configureStore();
let store;
let container;
beforeEach(() => {
store = mockStore({
authentication: { ...initialAuthenticationState }, // authentication.session is false in the initialAuthenticationState
});
container = shallow(
<MemoryRouter>
<Provider store={store}>
<RestrictedRoute />
</Provider>,
</MemoryRouter>
);
})
test('redirects if not authenticated',() => {
expect(container.find(Redirect).length).toBe(1);
});
});
我得到下面的結果,這不是我所期待:
● <RestrictedRoute /> › redirects if not authenticated
expect(received).toBe(expected)
Expected value to be (using ===):
1
Received:
0
我錯過了什麼?