diff --git a/packages/csv-stringify/lib/api/index.js b/packages/csv-stringify/lib/api/index.js index 4f932fb3..1fb77be2 100644 --- a/packages/csv-stringify/lib/api/index.js +++ b/packages/csv-stringify/lib/api/index.js @@ -161,12 +161,11 @@ const stringifier = function (options, state, info) { value !== undefined && value !== null ) { - if (err) - return [ - Error( - `Invalid Casting Value: returned value must return a string, null or undefined, got ${JSON.stringify(value)}`, - ), - ]; + return [ + Error( + `Invalid Casting Value: returned value must return a string, null or undefined, got ${JSON.stringify(value)}`, + ), + ]; } // Merge global options with the ones returned by cast options = { ...this.options, ...options }; diff --git a/packages/csv-stringify/test/option.cast.js b/packages/csv-stringify/test/option.cast.js index 643c3c24..83fcef78 100644 --- a/packages/csv-stringify/test/option.cast.js +++ b/packages/csv-stringify/test/option.cast.js @@ -1,5 +1,6 @@ import "should"; import { stringify } from "../lib/index.js"; +import { stringify as stringifySync } from "../lib/sync.js"; describe("Option `cast`", function () { describe("udf", function () { @@ -22,6 +23,29 @@ describe("Option `cast`", function () { }); describe("info object", function () { + for (const value of [0, false]) { + const message = `Invalid Casting Value: returned value must return a string, null or undefined, got ${JSON.stringify(value)}`; + + it(`reject invalid value ${JSON.stringify(value)} in the callback API`, function (next) { + stringify( + [["input"]], + { cast: { string: () => ({ value }) } }, + (err) => { + if (!err) + return next(Error("Expected an invalid casting value error")); + err.message.should.eql(message); + next(); + }, + ); + }); + + it(`reject invalid value ${JSON.stringify(value)} in the sync API`, function () { + (function () { + stringifySync([["input"]], { cast: { string: () => ({ value }) } }); + }).should.throw({ message }); + }); + } + it("validate and normalize local options", function (next) { stringify( [["invalid cast"]], diff --git a/packages/csv-stringify/test/option.cast.ts b/packages/csv-stringify/test/option.cast.ts index 56ea047e..5d27be58 100644 --- a/packages/csv-stringify/test/option.cast.ts +++ b/packages/csv-stringify/test/option.cast.ts @@ -195,6 +195,24 @@ describe("Option `cast`", function () { }); describe("info object", function () { + it("accept string, null and undefined values in cast options", function (next) { + stringify( + [["empty", "null", "undefined", "text"]], + { + cast: { + string: (value, context) => ({ + value: ["", null, undefined, "text"][context.index], + }), + }, + }, + (err, data) => { + if (err) return next(err); + data.should.eql(",,,text\n"); + next(); + }, + ); + }); + it("preserves a reused cast result", function (next) { const result = { value: "shared", quoted: true }; stringify(