Skip to content

Commit dd2cd6b

Browse files
authored
feat: add warn (#596)
* feat: add warn * test: add test for warn
1 parent 49766bf commit dd2cd6b

File tree

5 files changed

+47
-2
lines changed

5 files changed

+47
-2
lines changed

src/apis/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,3 +30,4 @@ export { useCSSModule } from './useCssModule'
3030
export { createApp } from './createApp'
3131
export { nextTick } from './nextTick'
3232
export { createElement as h } from './createElement'
33+
export { warn } from './warn'

src/apis/warn.ts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import { getCurrentInstance } from '../runtimeContext'
2+
import { warn as vueWarn } from '../utils'
3+
4+
/**
5+
* Displays a warning message (using console.error) with a stack trace if the
6+
* function is called inside of active component.
7+
*
8+
* @param message warning message to be displayed
9+
*/
10+
export function warn(message: string) {
11+
vueWarn(message, getCurrentInstance())
12+
}

src/env.d.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ declare module 'vue/types/vue' {
1919
interface VueConstructor {
2020
observable<T>(x: any): T
2121
util: {
22-
warn(msg: string, vm?: Vue)
22+
warn(msg: string, vm?: Vue | null)
2323
defineReactive(
2424
obj: Object,
2525
key: string,

src/utils/utils.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ export function isUndef(v: any): boolean {
8383
return v === undefined || v === null
8484
}
8585

86-
export function warn(msg: string, vm?: Vue) {
86+
export function warn(msg: string, vm?: Vue | null) {
8787
Vue.util.warn(msg, vm)
8888
}
8989

test/apis/warn.spec.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
const Vue = require('vue/dist/vue.common.js')
2+
const { warn: apiWarn } = require('../../src')
3+
4+
describe('api/warn', () => {
5+
beforeEach(() => {
6+
warn = jest.spyOn(global.console, 'error').mockImplementation(() => null)
7+
})
8+
afterEach(() => {
9+
warn.mockRestore()
10+
})
11+
12+
it('can be called inside a component', () => {
13+
new Vue({
14+
setup() {
15+
apiWarn('warned')
16+
},
17+
template: `<div></div>`,
18+
}).$mount()
19+
20+
expect(warn).toHaveBeenCalledTimes(1)
21+
expect(warn.mock.calls[0][0]).toMatch(
22+
/\[Vue warn\]: warned[\s\S]*\(found in <Root>\)/
23+
)
24+
})
25+
26+
it('can be called outside a component', () => {
27+
apiWarn('warned')
28+
29+
expect(warn).toHaveBeenCalledTimes(1)
30+
expect(warn).toHaveBeenCalledWith('[Vue warn]: warned')
31+
})
32+
})

0 commit comments

Comments
 (0)