Yang Guo | 4fd355c | 2019-09-19 10:59:03 +0200 | [diff] [blame^] | 1 | 'use strict'; |
| 2 | |
| 3 | var test = require('tape'); |
| 4 | var stringify = require('../'); |
| 5 | |
| 6 | test('nested', function (t) { |
| 7 | t.plan(1); |
| 8 | var obj = { c: 8, b: [{z:6,y:5,x:4},7], a: 3 }; |
| 9 | t.equal(stringify(obj), '{"a":3,"b":[{"x":4,"y":5,"z":6},7],"c":8}'); |
| 10 | }); |
| 11 | |
| 12 | test('cyclic (default)', function (t) { |
| 13 | t.plan(1); |
| 14 | var one = { a: 1 }; |
| 15 | var two = { a: 2, one: one }; |
| 16 | one.two = two; |
| 17 | try { |
| 18 | stringify(one); |
| 19 | } catch (ex) { |
| 20 | t.equal(ex.toString(), 'TypeError: Converting circular structure to JSON'); |
| 21 | } |
| 22 | }); |
| 23 | |
| 24 | test('cyclic (specifically allowed)', function (t) { |
| 25 | t.plan(1); |
| 26 | var one = { a: 1 }; |
| 27 | var two = { a: 2, one: one }; |
| 28 | one.two = two; |
| 29 | t.equal(stringify(one, {cycles:true}), '{"a":1,"two":{"a":2,"one":"__cycle__"}}'); |
| 30 | }); |
| 31 | |
| 32 | test('repeated non-cyclic value', function(t) { |
| 33 | t.plan(1); |
| 34 | var one = { x: 1 }; |
| 35 | var two = { a: one, b: one }; |
| 36 | t.equal(stringify(two), '{"a":{"x":1},"b":{"x":1}}'); |
| 37 | }); |
| 38 | |
| 39 | test('acyclic but with reused obj-property pointers', function (t) { |
| 40 | t.plan(1); |
| 41 | var x = { a: 1 }; |
| 42 | var y = { b: x, c: x }; |
| 43 | t.equal(stringify(y), '{"b":{"a":1},"c":{"a":1}}'); |
| 44 | }); |