From dd2cd6b56e6a6cc454391b9e0d07291a5bbcc623 Mon Sep 17 00:00:00 2001 From: Eduardo San Martin Morote Date: Tue, 24 Nov 2020 00:25:21 +0100 Subject: [PATCH] feat: add warn (#596) * feat: add warn * test: add test for warn --- src/apis/index.ts | 1 + src/apis/warn.ts | 12 ++++++++++++ src/env.d.ts | 2 +- src/utils/utils.ts | 2 +- test/apis/warn.spec.js | 32 ++++++++++++++++++++++++++++++++ 5 files changed, 47 insertions(+), 2 deletions(-) create mode 100644 src/apis/warn.ts create mode 100644 test/apis/warn.spec.js diff --git a/src/apis/index.ts b/src/apis/index.ts index bf2e31e2..d1821026 100644 --- a/src/apis/index.ts +++ b/src/apis/index.ts @@ -30,3 +30,4 @@ export { useCSSModule } from './useCssModule' export { createApp } from './createApp' export { nextTick } from './nextTick' export { createElement as h } from './createElement' +export { warn } from './warn' diff --git a/src/apis/warn.ts b/src/apis/warn.ts new file mode 100644 index 00000000..2bb5236f --- /dev/null +++ b/src/apis/warn.ts @@ -0,0 +1,12 @@ +import { getCurrentInstance } from '../runtimeContext' +import { warn as vueWarn } from '../utils' + +/** + * Displays a warning message (using console.error) with a stack trace if the + * function is called inside of active component. + * + * @param message warning message to be displayed + */ +export function warn(message: string) { + vueWarn(message, getCurrentInstance()) +} diff --git a/src/env.d.ts b/src/env.d.ts index 161e9a67..8e362480 100644 --- a/src/env.d.ts +++ b/src/env.d.ts @@ -19,7 +19,7 @@ declare module 'vue/types/vue' { interface VueConstructor { observable(x: any): T util: { - warn(msg: string, vm?: Vue) + warn(msg: string, vm?: Vue | null) defineReactive( obj: Object, key: string, diff --git a/src/utils/utils.ts b/src/utils/utils.ts index 0bffd6d7..2c4f4fc1 100644 --- a/src/utils/utils.ts +++ b/src/utils/utils.ts @@ -83,7 +83,7 @@ export function isUndef(v: any): boolean { return v === undefined || v === null } -export function warn(msg: string, vm?: Vue) { +export function warn(msg: string, vm?: Vue | null) { Vue.util.warn(msg, vm) } diff --git a/test/apis/warn.spec.js b/test/apis/warn.spec.js new file mode 100644 index 00000000..9ceb5fa9 --- /dev/null +++ b/test/apis/warn.spec.js @@ -0,0 +1,32 @@ +const Vue = require('vue/dist/vue.common.js') +const { warn: apiWarn } = require('../../src') + +describe('api/warn', () => { + beforeEach(() => { + warn = jest.spyOn(global.console, 'error').mockImplementation(() => null) + }) + afterEach(() => { + warn.mockRestore() + }) + + it('can be called inside a component', () => { + new Vue({ + setup() { + apiWarn('warned') + }, + template: `
`, + }).$mount() + + expect(warn).toHaveBeenCalledTimes(1) + expect(warn.mock.calls[0][0]).toMatch( + /\[Vue warn\]: warned[\s\S]*\(found in \)/ + ) + }) + + it('can be called outside a component', () => { + apiWarn('warned') + + expect(warn).toHaveBeenCalledTimes(1) + expect(warn).toHaveBeenCalledWith('[Vue warn]: warned') + }) +})