Skip to content

Commit

Permalink
feat(utils): add warn function (#3147)
Browse files Browse the repository at this point in the history
* feat(utils): add warn function

* test(utils): use calledWith
  • Loading branch information
samouss authored Sep 25, 2018
1 parent a68cdaf commit 9de87bb
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 3 deletions.
34 changes: 33 additions & 1 deletion src/lib/__tests__/utils-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -876,7 +876,7 @@ describe('utils.deprecate', () => {
const actual = 6;

expect(actual).toBe(expectation);
expect(warn).toHaveBeenCalled();
expect(warn).toHaveBeenCalledWith('[InstantSearch.js]: message');

warn.mockReset();
warn.mockRestore();
Expand All @@ -899,6 +899,38 @@ describe('utils.deprecate', () => {
});
});

describe('utils.warn', () => {
it('expect to print a warn message', () => {
const message = 'message';
const warn = jest.spyOn(global.console, 'warn');

utils.warn(message);

expect(warn).toHaveBeenCalledWith('[InstantSearch.js]: message');

warn.mockReset();
warn.mockRestore();
utils.warn.cache = {};
});

it('expect to print the same message only once', () => {
const message = 'message';
const warn = jest.spyOn(global.console, 'warn');

utils.warn(message);

expect(warn).toHaveBeenCalledTimes(1);

utils.warn(message);

expect(warn).toHaveBeenCalledTimes(1);

warn.mockReset();
warn.mockRestore();
utils.warn.cache = {};
});
});

describe('utils.parseAroundLatLngFromString', () => {
it('expect to return a LatLng object from string', () => {
const samples = [
Expand Down
20 changes: 18 additions & 2 deletions src/lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export {
checkRendering,
isReactElement,
deprecate,
warn,
parseAroundLatLngFromString,
};

Expand Down Expand Up @@ -401,21 +402,36 @@ function isReactElement(object) {
);
}

function logger(message) {
// eslint-disable-next-line no-console
console.warn(`[InstantSearch.js]: ${message.trim()}`);
}

function deprecate(fn, message) {
let hasAlreadyPrint = false;

return function(...args) {
if (!hasAlreadyPrint) {
hasAlreadyPrint = true;

// eslint-disable-next-line no-console
console.warn(`[InstantSearch.js]: ${message}`);
logger(message);
}

return fn(...args);
};
}

warn.cache = {};
function warn(message) {
const hasAlreadyPrint = warn.cache[message];

if (!hasAlreadyPrint) {
warn.cache[message] = true;

logger(message);
}
}

const latLngRegExp = /^(-?\d+(?:\.\d+)?),\s*(-?\d+(?:\.\d+)?)$/;
function parseAroundLatLngFromString(value) {
const pattern = value.match(latLngRegExp);
Expand Down

0 comments on commit 9de87bb

Please sign in to comment.