|
5 | 5 | package js_test
|
6 | 6 |
|
7 | 7 | import (
|
| 8 | + "fmt" |
8 | 9 | "math"
|
9 | 10 | "testing"
|
10 | 11 |
|
@@ -167,3 +168,57 @@ func TestType(t *testing.T) {
|
167 | 168 | t.Errorf("got %s, want %s", got, want)
|
168 | 169 | }
|
169 | 170 | }
|
| 171 | + |
| 172 | +func TestValueOf(t *testing.T) { |
| 173 | + for _, test := range []struct { |
| 174 | + in interface{} |
| 175 | + wantType js.Type |
| 176 | + wantString string |
| 177 | + }{ |
| 178 | + {js.Value(js.ValueOf(42)), js.TypeNumber, "42"}, |
| 179 | + {js.NewCallback(func(args []js.Value) {}), js.TypeFunction, ""}, |
| 180 | + {js.TypedArrayOf([]int8{1, 2, 3}), js.TypeObject, "1,2,3"}, |
| 181 | + {nil, js.TypeNull, "null"}, |
| 182 | + {bool(true), js.TypeBoolean, "true"}, |
| 183 | + {int(1), js.TypeNumber, "1"}, |
| 184 | + {int8(2), js.TypeNumber, "2"}, |
| 185 | + {int16(3), js.TypeNumber, "3"}, |
| 186 | + {int32(4), js.TypeNumber, "4"}, |
| 187 | + {int64(5), js.TypeNumber, "5"}, |
| 188 | + {uint(6), js.TypeNumber, "6"}, |
| 189 | + {uint8(7), js.TypeNumber, "7"}, |
| 190 | + {uint16(8), js.TypeNumber, "8"}, |
| 191 | + {uint32(9), js.TypeNumber, "9"}, |
| 192 | + {uint64(10), js.TypeNumber, "10"}, |
| 193 | + {float32(11), js.TypeNumber, "11"}, |
| 194 | + {float64(12), js.TypeNumber, "12"}, |
| 195 | + // FIXME this doesn't work {unsafe.Pointer(&x19), js.TypeNumber, ""}, |
| 196 | + {string("hello"), js.TypeString, "hello"}, |
| 197 | + {map[string]interface{}{"a": 1, "b": "c"}, js.TypeObject, "[object Object]"}, |
| 198 | + {[]interface{}{1, 2, 3}, js.TypeObject, "1,2,3"}, |
| 199 | + } { |
| 200 | + t.Run(fmt.Sprintf("%T", test.in), func(t *testing.T) { |
| 201 | + got := js.ValueOf(test.in) |
| 202 | + if got.Type() != test.wantType { |
| 203 | + t.Errorf("type: got %v want %v", got.Type(), test.wantType) |
| 204 | + } |
| 205 | + if test.wantString != "" && got.String() != test.wantString { |
| 206 | + t.Errorf("string: got %v want %v", got.String(), test.wantString) |
| 207 | + } |
| 208 | + }) |
| 209 | + } |
| 210 | + |
| 211 | + // Check unknown types panic |
| 212 | + didPanic := false |
| 213 | + func() { |
| 214 | + defer func() { |
| 215 | + if r := recover(); r != nil { |
| 216 | + didPanic = true |
| 217 | + } |
| 218 | + }() |
| 219 | + _ = js.ValueOf([]struct{}{}) |
| 220 | + }() |
| 221 | + if !didPanic { |
| 222 | + t.Errorf("Unknown type didn't panic") |
| 223 | + } |
| 224 | +} |
0 commit comments