diff --git a/src/request-base.js b/src/request-base.js index cd6020bb..a2649979 100644 --- a/src/request-base.js +++ b/src/request-base.js @@ -662,7 +662,8 @@ RequestBase.prototype.send = function (data) { // merge if (isObject_ && isObject(this._data)) { for (const key in data) { - if (typeof data[key] == "bigint") throw new Error("Cannot serialize BigInt value to json"); + if (typeof data[key] == 'bigint' && !data[key].toJSON) + throw new Error('Cannot serialize BigInt value to json'); if (hasOwn(data, key)) this._data[key] = data[key]; } } diff --git a/test/json.js b/test/json.js index 3d10d7b4..967c3904 100644 --- a/test/json.js +++ b/test/json.js @@ -132,6 +132,32 @@ describe('req.send(Object) as "json"', function () { done(); }); + describe('when BigInts have a .toJSON property', function () { + before(function () { + // eslint-disable-next-line node/no-unsupported-features/es-builtins + BigInt.prototype.toJSON = function () { + return this.toString(); + }; + }); + + it('should accept BigInt properties', (done) => { + request + .post(`${uri}/echo`) + .send({ number: 1n }) + .end((error, res) => { + res.should.be.json(); + res.text.should.equal('{"number":"1"}'); + done(); + }); + }); + + after(function () { + // eslint-disable-next-line node/no-unsupported-features/es-builtins + delete BigInt.prototype.toJSON; + }); + }); + + it('should error for BigInt primitive', (done) => { try { request