diff --git a/utils/convert.go b/utils/convert.go index 0c2d443ecb16b9992b3f87805b4833935bdaeb2a..a5c79e309529089ebb918fc77f701f7a633c8d05 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 8cbbf2555c307c782bb3f52168c12ec307633fd4..74bd9ca6c68e5e95639f413f2da0ab58b5faed31 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) {