Skip to content

Commit

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

* test: add test for warn
  • Loading branch information
posva committed Nov 23, 2020
1 parent 49766bf commit dd2cd6b
Show file tree
Hide file tree
Showing 5 changed files with 47 additions and 2 deletions.
1 change: 1 addition & 0 deletions src/apis/index.ts
Expand Up @@ -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'
12 changes: 12 additions & 0 deletions 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())
}
2 changes: 1 addition & 1 deletion src/env.d.ts
Expand Up @@ -19,7 +19,7 @@ declare module 'vue/types/vue' {
interface VueConstructor {
observable<T>(x: any): T
util: {
warn(msg: string, vm?: Vue)
warn(msg: string, vm?: Vue | null)
defineReactive(
obj: Object,
key: string,
Expand Down
2 changes: 1 addition & 1 deletion src/utils/utils.ts
Expand Up @@ -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)
}

Expand Down
32 changes: 32 additions & 0 deletions 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: `<div></div>`,
}).$mount()

expect(warn).toHaveBeenCalledTimes(1)
expect(warn.mock.calls[0][0]).toMatch(
/\[Vue warn\]: warned[\s\S]*\(found in <Root>\)/
)
})

it('can be called outside a component', () => {
apiWarn('warned')

expect(warn).toHaveBeenCalledTimes(1)
expect(warn).toHaveBeenCalledWith('[Vue warn]: warned')
})
})

0 comments on commit dd2cd6b

Please sign in to comment.