fix(shared): support custom .toString() in text interpolation again (#4210)

fix #3944
This commit is contained in:
Roan Kattouw 2021-07-29 10:51:03 -04:00 committed by GitHub
parent 1e3d468ca1
commit 9d5fd33d6d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 22 additions and 3 deletions

View File

@ -31,10 +31,22 @@ describe('toDisplayString', () => {
})
).toBe(JSON.stringify({ n: 1, np: 2 }, null, 2))
})
test('objects with custom toString', () => {
class TestClass {
toString() {
return 'foo'
}
}
const instance = new TestClass()
expect(toDisplayString(instance)).toBe('foo')
const obj = { toString: () => 'bar' }
expect(toDisplayString(obj)).toBe('bar')
})
test('native objects', () => {
const div = document.createElement('div')
expect(toDisplayString(div)).toBe(`"[object HTMLDivElement]"`)
expect(toDisplayString(div)).toBe('[object HTMLDivElement]')
expect(toDisplayString({ div })).toMatchInlineSnapshot(`
"{
\\"div\\": \\"[object HTMLDivElement]\\"

View File

@ -1,4 +1,11 @@
import { isArray, isMap, isObject, isPlainObject, isSet } from './index'
import {
isArray,
isMap,
isObject,
isPlainObject,
isSet,
objectToString
} from './index'
/**
* For converting {{ interpolation }} values to displayed strings.
@ -7,7 +14,7 @@ import { isArray, isMap, isObject, isPlainObject, isSet } from './index'
export const toDisplayString = (val: unknown): string => {
return val == null
? ''
: isObject(val)
: isArray(val) || (isObject(val) && val.toString === objectToString)
? JSON.stringify(val, replacer, 2)
: String(val)
}