Skip to content

Commit

Permalink
up coverage
Browse files Browse the repository at this point in the history
  • Loading branch information
Dereje1 committed Jan 18, 2023
1 parent 98edd13 commit 4502ec8
Show file tree
Hide file tree
Showing 8 changed files with 103 additions and 15 deletions.
1 change: 0 additions & 1 deletion __mocks__/axios.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

module.exports = {
get: (...args) => {
const route = args[0];
Expand Down
2 changes: 2 additions & 0 deletions client/src/__mocks__/crud.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ const restMock = jest.fn().mockImplementation((...args) => {
_id: 2,
tags: [{ _id: 6, tag: 'tester tag' }],
});
} if (address.includes('/api/getTags') && method === 'get' && !payload) {
return Promise.resolve(['TAG 3', 'TAG 4']);
}
return Promise.reject(new Error(`Requested method:${method} and path: ${address} not mocked!!`));
});
Expand Down
4 changes: 2 additions & 2 deletions client/src/components/modal/TagsForm.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ function TagsForm({

return (
<div style={{
width: 300,
width: 200,
marginLeft: 'auto',
marginRight: 'auto',
display: 'flex',
Expand All @@ -49,7 +49,7 @@ function TagsForm({
options={suggestedTags.map((option) => option.toUpperCase())}
fullWidth
disableClearable
value={tag}
inputValue={tag}
autoComplete
onInputChange={handleTag}
onBlur={closeTagsForm}
Expand Down
3 changes: 2 additions & 1 deletion server/crudroutes.js
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ const updateTags = async (req, res) => {
}
const updatedPin = await pins.findByIdAndUpdate(pinID, update, { new: true }).exec();
const [filteredAndUpdatedPin] = filterPins({ rawPins: [updatedPin], userId, isAdmin });
console.log(`${displayName} ${deleteId ? 'deleted' : 'added'} tag on ${updatedPin.imgDescription}`);
console.log(`${displayName} ${deleteId ? 'deleted' : `added ${tag}`} tag on ${updatedPin.imgDescription}`);
res.json(filteredAndUpdatedPin);
} catch (error) {
res.json(error);
Expand Down Expand Up @@ -266,4 +266,5 @@ module.exports = {
getProfilePins,
getUserPins,
updateTags,
getTags,
};
27 changes: 24 additions & 3 deletions tests/client/src/components/modal/Tags.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ import toJson from 'enzyme-to-json';
import { useHistory } from 'react-router-dom';
import Tags, { ListItem } from '../../../../../client/src/components/modal/Tags';
import { pinsStub } from '../../../pinsStub';
import RESTcall from '../../../../../client/src/crud';

jest.mock('../../../../../client/src/crud');

const mockdispatch = jest.fn();
// Mock router hooks
Expand Down Expand Up @@ -52,21 +55,39 @@ describe('The tags component', () => {
expect(toJson(wrapper)).toMatchSnapshot();
});

test('will open and close the form to add tags', () => {
test('will open and close the form to add tags', async () => {
const wrapper = shallow(<Tags {...props} />);
const addTags = wrapper.find('ForwardRef(IconButton)');
let tagsForm = wrapper.find('TagsForm');
expect(tagsForm.isEmptyRender()).toBe(true);
// trigger form show
addTags.props().onClick();
// trigger form show and test tags fetch
await addTags.props().onClick();
tagsForm = wrapper.find('TagsForm');
expect(tagsForm.isEmptyRender()).toBe(false);
expect(RESTcall).toHaveBeenCalledWith({
address: '/api/getTags',
});
expect(tagsForm.props().suggestedTags).toEqual(['TAG 3', 'TAG 4']);
// trigger form close
tagsForm.props().closeTagsForm();
tagsForm = wrapper.find('TagsForm');
expect(tagsForm.isEmptyRender()).toBe(true);
});

test('will add no suggested tags if rest call is rejected', async () => {
RESTcall.mockImplementationOnce(() => Promise.reject());
const wrapper = shallow(<Tags {...props} />);
const addTags = wrapper.find('ForwardRef(IconButton)');
// trigger form show and add tag
await addTags.props().onClick();
const tagsForm = wrapper.find('TagsForm');
expect(tagsForm.isEmptyRender()).toBe(false);
expect(RESTcall).toHaveBeenCalledWith({
address: '/api/getTags',
});
expect(tagsForm.props().suggestedTags).toEqual([]);
});

test('will add a tag', () => {
const wrapper = shallow(<Tags {...props} />);
const addTags = wrapper.find('ForwardRef(IconButton)');
Expand Down
34 changes: 28 additions & 6 deletions tests/client/src/components/modal/TagsForm.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ describe('The tags form component', () => {
props = {
addTag: jest.fn(),
closeTagsForm: jest.fn(),
suggestedTags: ['suggested tag 1', 'suggested tag 2'],
exisitingTags: ['existing tag 1', 'existing tag 2'],
suggestedTags: ['SUGGESTED TAG 1', 'SUGGESTED TAG 2'],
exisitingTags: ['EXISTING TAG 1', 'EXISTING TAG 2'],
};
});

Expand All @@ -26,21 +26,21 @@ describe('The tags form component', () => {
test('will update the value for characters <= 15', () => {
const wrapper = shallow(<TagsForm {...props} />);
let autoComplete = wrapper.find('ForwardRef(Autocomplete)');
expect(autoComplete.props().value).toBe('');
expect(autoComplete.props().inputValue).toBe('');
// trigger value change
autoComplete.props().onInputChange('', '15 characters..');
autoComplete = wrapper.find('ForwardRef(Autocomplete)');
expect(autoComplete.props().value).toBe('15 characters..');
expect(autoComplete.props().inputValue).toBe('15 characters..');
});

test('will not update the value for characters > 15', () => {
const wrapper = shallow(<TagsForm {...props} />);
let autoComplete = wrapper.find('ForwardRef(Autocomplete)');
expect(autoComplete.props().value).toBe('');
expect(autoComplete.props().inputValue).toBe('');
// trigger value change
autoComplete.props().onInputChange('', '16 characters..and more');
autoComplete = wrapper.find('ForwardRef(Autocomplete)');
expect(autoComplete.props().value).toBe('');
expect(autoComplete.props().inputValue).toBe('');
});

test('will submit on done if value is present', () => {
Expand Down Expand Up @@ -88,4 +88,26 @@ describe('The tags form component', () => {
autoComplete.props().onKeyDown({ key: 'other key' });
expect(props.addTag).not.toHaveBeenCalled();
});

test('autocomplete will filter the options present for auto complete', () => {
const wrapper = shallow(<TagsForm {...props} />);
let autoComplete = wrapper.find('ForwardRef(Autocomplete)');
autoComplete.props().onInputChange('', 'sug');
autoComplete = wrapper.find('ForwardRef(Autocomplete)');
const filtered = autoComplete.props().filterOptions(['SUGGESTED TAG 1', 'EXISTING TAG 2']);
expect(filtered).toEqual(['SUGGESTED TAG 1']);
});

test('autocomplete will render the text field as input', () => {
const wrapper = shallow(<TagsForm {...props} />);
const autoComplete = wrapper.find('ForwardRef(Autocomplete)');
const textfield = autoComplete.props().renderInput({});
expect(textfield.props).toEqual({
autoFocus: true,
id: 'Tags_form',
label: 'Add a Tag',
type: 'text',
variant: 'standard',
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ exports[`The tags form component will render 1`] = `
"display": "flex",
"marginLeft": "auto",
"marginRight": "auto",
"width": 300,
"width": 200,
}
}
>
Expand All @@ -19,6 +19,7 @@ exports[`The tags form component will render 1`] = `
freeSolo={true}
fullWidth={true}
id="free-solo-tags"
inputValue=""
onBlur={[MockFunction]}
onInputChange={[Function]}
onKeyDown={[Function]}
Expand All @@ -29,7 +30,6 @@ exports[`The tags form component will render 1`] = `
]
}
renderInput={[Function]}
value=""
/>
<Memo(ForwardRef(DoneIcon))
color="success"
Expand Down
43 changes: 43 additions & 0 deletions tests/server/crudroutes.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const {
getProfilePins,
getUserPins,
updateTags,
getTags,
} = require('../../server/crudroutes');
const pins = require('../../server/models/pins'); // schema for pins
const users = require('../../server/models/user'); // schema for pins
Expand Down Expand Up @@ -853,3 +854,45 @@ describe('Updating tags for a pin', () => {
expect(res.json).toHaveBeenCalledWith(Error('Mocked rejection'));
});
});

describe('Getting saved tags list', () => {
let res;
beforeEach(() => {
res = { json: jest.fn() };
process.env = {
...process.env,
ADMIN_USER_ID: 'xxx',
};
});
afterEach(() => {
jest.restoreAllMocks();
});

test('will get tags', async () => {
const distinct = jest.fn();
savedTags.find = jest.fn().mockImplementation(
() => ({
distinct: distinct.mockImplementation(() => ({
exec: jest.fn().mockResolvedValue(['saved tags']),
})),
}),
);
await getTags({}, res);
expect(savedTags.find).toHaveBeenCalledTimes(1);
expect(distinct).toHaveBeenCalledWith('tag');
expect(res.json).toHaveBeenCalledWith(['saved tags']);
});

xtest('will respond with error if get is rejected', async () => {
const req = {};
savedTags.find = jest.fn().mockImplementation(
() => ({
distinct: jest.fn().mockImplementation(() => ({
exec: jest.fn().mockRejectedValue(new Error('Mocked rejection')),
})),
}),
);
await getTags(req, res);
expect(res.json).toHaveBeenCalledWith(Error('Mocked rejection'));
});
});

0 comments on commit 4502ec8

Please sign in to comment.