From b33d17d057db72cd52f42c066379536f52769109 Mon Sep 17 00:00:00 2001 From: Jono Wenger <jono@elixxir.io> Date: Mon, 19 Dec 2022 11:35:05 -0800 Subject: [PATCH] Make JsToJson return valid JSON when the Javascript value is undefined --- utils/convert.go | 4 ++++ utils/convert_test.go | 16 ++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/utils/convert.go b/utils/convert.go index 0c2d443e..a5c79e30 100644 --- a/utils/convert.go +++ b/utils/convert.go @@ -32,6 +32,10 @@ func CopyBytesToJS(src []byte) js.Value { // JsToJson converts the Javascript value to JSON. func JsToJson(value js.Value) string { + if value.IsUndefined() { + return "null" + } + return JSON.Call("stringify", value).String() } diff --git a/utils/convert_test.go b/utils/convert_test.go index 8cbbf255..74bd9ca6 100644 --- a/utils/convert_test.go +++ b/utils/convert_test.go @@ -113,6 +113,22 @@ func TestJsToJson(t *testing.T) { } } +// Tests that JsToJson return a null object when the Javascript object is +// undefined. +func TestJsToJson_Undefined(t *testing.T) { + expected, err := json.Marshal(nil) + if err != nil { + t.Errorf("Failed to JSON marshal test object: %+v", err) + } + + jsJson := JsToJson(js.Undefined()) + + if string(expected) != jsJson { + t.Errorf("Recieved incorrect JSON from Javascript object."+ + "\nexpected: %s\nreceived: %s", expected, jsJson) + } +} + // Tests that JsonToJS can convert a JSON object with multiple types to a // Javascript object and that all values match. func TestJsonToJS(t *testing.T) { -- GitLab