mirror of
https://github.com/grafana/grafana.git
synced 2025-02-25 18:55:37 -06:00
Utils: avoid calling console.warn() too often for deprecation warnings (#18269)
This commit is contained in:
parent
8c49d27705
commit
4ce814ba94
34
packages/grafana-ui/src/utils/deprecationWarning.test.ts
Normal file
34
packages/grafana-ui/src/utils/deprecationWarning.test.ts
Normal file
@ -0,0 +1,34 @@
|
||||
import { deprecationWarning } from './deprecationWarning';
|
||||
|
||||
test('It should not output deprecation warnings too often', () => {
|
||||
let dateNowValue = 10000000;
|
||||
|
||||
const spyConsoleWarn = jest.spyOn(console, 'warn').mockImplementation();
|
||||
const spyDateNow = jest.spyOn(global.Date, 'now').mockImplementation(() => dateNowValue);
|
||||
// Make sure the mock works
|
||||
expect(Date.now()).toEqual(dateNowValue);
|
||||
expect(console.warn).toHaveBeenCalledTimes(0);
|
||||
|
||||
// Call the deprecation many times
|
||||
deprecationWarning('file', 'oldName', 'newName');
|
||||
deprecationWarning('file', 'oldName', 'newName');
|
||||
deprecationWarning('file', 'oldName', 'newName');
|
||||
deprecationWarning('file', 'oldName', 'newName');
|
||||
deprecationWarning('file', 'oldName', 'newName');
|
||||
expect(console.warn).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Increment the time by 1min
|
||||
dateNowValue += 60000;
|
||||
deprecationWarning('file', 'oldName', 'newName');
|
||||
deprecationWarning('file', 'oldName', 'newName');
|
||||
expect(console.warn).toHaveBeenCalledTimes(2);
|
||||
|
||||
deprecationWarning('file2', 'oldName', 'newName');
|
||||
deprecationWarning('file2', 'oldName', 'newName');
|
||||
deprecationWarning('file2', 'oldName', 'newName');
|
||||
expect(console.warn).toHaveBeenCalledTimes(3);
|
||||
|
||||
// or restoreMocks automatically?
|
||||
spyConsoleWarn.mockRestore();
|
||||
spyDateNow.mockRestore();
|
||||
});
|
@ -1,7 +1,17 @@
|
||||
import { KeyValue } from '../types/index';
|
||||
|
||||
// Avoid writing the warning message more than once every 10s
|
||||
const history: KeyValue<number> = {};
|
||||
|
||||
export const deprecationWarning = (file: string, oldName: string, newName?: string) => {
|
||||
let message = `[Deprecation warning] ${file}: ${oldName} is deprecated`;
|
||||
if (newName) {
|
||||
message += `. Use ${newName} instead`;
|
||||
}
|
||||
console.warn(message);
|
||||
const now = Date.now();
|
||||
const last = history[message];
|
||||
if (!last || now - last > 10000) {
|
||||
console.warn(message);
|
||||
history[message] = now;
|
||||
}
|
||||
};
|
||||
|
@ -229,7 +229,7 @@ kbn.slugifyForUrl = str => {
|
||||
.replace(/ +/g, '-');
|
||||
};
|
||||
|
||||
/** deprecated since 6.1, use grafana/ui */
|
||||
/** deprecated since 6.1, use grafana/data */
|
||||
kbn.stringToJsRegex = str => {
|
||||
deprecationWarning('kbn.ts', 'kbn.stringToJsRegex()', '@grafana/data');
|
||||
return stringToJsRegex(str);
|
||||
|
Loading…
Reference in New Issue
Block a user