Skip to content

Instantly share code, notes, and snippets.

@emil-alexandrescu
Created March 19, 2019 20:52
Show Gist options
  • Save emil-alexandrescu/f52137bd94bf9dc9ad05b06b719b0c57 to your computer and use it in GitHub Desktop.
Save emil-alexandrescu/f52137bd94bf9dc9ad05b06b719b0c57 to your computer and use it in GitHub Desktop.
/* eslint-disable react/display-name */
import React from 'react';
import { shallow } from 'enzyme';
import { Redirect } from 'react-router';
import withAuthGuard from '../withAuthGuard';
jest.mock('../withUser');
import withUser from '../withUser';
const AnyComponent = () => <div>Emil is Awesome</div>;
describe('@common/hocs/auth/withAuthGuard', () => {
const create = (redirectTo, roles) => {
const AnyComponentWithHOC = withAuthGuard(redirectTo, roles)(AnyComponent);
return shallow(<AnyComponentWithHOC />);
};
it('should be a function', () => {
expect(typeof withAuthGuard).toBe('function');
});
it('should return a hoc', () => {
expect(typeof withAuthGuard()).toBe('function');
});
describe('when user is not logged in', () => {
beforeEach(() => {
withUser.mockImplementation(ComposedComponent => () => (
<ComposedComponent currentUser={null} />
));
});
it('should redirect to login', () => {
const wrapper = create().dive();
expect(wrapper.is(Redirect)).toBe(true);
expect(wrapper.prop('to')).toBe('/login');
});
it('should redirect to specified path', () => {
const wrapper = create('/random-path').dive();
expect(wrapper.is(Redirect)).toBe(true);
expect(wrapper.prop('to')).toBe('/random-path');
});
});
describe('when user is logged in', () => {
describe('when user is admin', () => {
beforeEach(() => {
withUser.mockImplementation(ComposedComponent => () => (
<ComposedComponent currentUser={{ role: 'admin' }} />
));
});
it('should render component when role is not guarded', () => {
const wrapper = create('/random-path').dive();
expect(wrapper.is(AnyComponent)).toBe(true);
});
it('should render component when role is guarded', () => {
const wrapper = create('/random-path', ['admin']).dive();
expect(wrapper.is(AnyComponent)).toBe(true);
});
});
describe('when user is not admin', () => {
beforeEach(() => {
withUser.mockImplementation(ComposedComponent => () => (
<ComposedComponent currentUser={{ role: 'user' }} />
));
});
it('should render component when role is not guarded', () => {
const wrapper = create('/random-path').dive();
expect(wrapper.is(AnyComponent)).toBe(true);
});
it('should redirect when role is guarded', () => {
const wrapper = create('/random-path', ['admin']).dive();
expect(wrapper.is(Redirect)).toBe(true);
expect(wrapper.prop('to')).toBe('/random-path');
});
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment