util: if present, fallback to toString using the %s formatter

This makes sure that `util.format` uses `String` to stringify an object
in case the object has an own property named `toString` with type
`function`. That way objects that do not have such function are still
inspected using `util.inspect` and the old behavior is preserved as
well.

PR-URL: https://github.com/nodejs/node/pull/27621
Refs: https://github.com/facebook/jest/issues/8443
Reviewed-By: Roman Reiss <me@silverwind.io>
This commit is contained in:
Ruben Bridgewater committed 2019-05-20 14:18:18 +02:00
1 parent 182b48aa77
commit 5518664d41
3 files changed
+55 -12

No files matched your search

+22
View File
@@ -138,8 +138,30 @@ assert.strictEqual(util.format('%s', 42n), '42n');
assert.strictEqual(util.format('%s', Symbol('foo')), 'Symbol(foo)');
assert.strictEqual(util.format('%s', true), 'true');
assert.strictEqual(util.format('%s', { a: [1, 2, 3] }), '{ a: [Array] }');
assert.strictEqual(util.format('%s', { toString() { return 'Foo'; } }), 'Foo');
assert.strictEqual(util.format('%s', { toString: 5 }), '{ toString: 5 }');
assert.strictEqual(util.format('%s', () => 5), '() => 5');
// String format specifier including `toString` properties on the prototype.
{
class Foo { toString() { return 'Bar'; } }
assert.strictEqual(util.format('%s', new Foo()), 'Bar');
assert.strictEqual(
util.format('%s', Object.setPrototypeOf(new Foo(), null)),
'[Foo: null prototype] {}'
);
global.Foo = Foo;
assert.strictEqual(util.format('%s', new Foo()), 'Bar');
delete global.Foo;
class Bar { abc = true; }
assert.strictEqual(util.format('%s', new Bar()), 'Bar { abc: true }');
class Foobar extends Array { aaa = true; }
assert.strictEqual(
util.format('%s', new Foobar(5)),
'Foobar [ <5 empty items>, aaa: true ]'
);
}
// JSON format specifier
assert.strictEqual(util.format('%j'), '%j');
assert.strictEqual(util.format('%j', 42), '42');