github.com/nuvolaris/goja@v0.0.0-20230825100449-967811910c6d/builtin_weakset_test.go (about)

     1  package goja
     2  
     3  import (
     4  	"testing"
     5  )
     6  
     7  func TestWeakSetBasic(t *testing.T) {
     8  	const SCRIPT = `
     9  	var s = new WeakSet();
    10  	var o = {};
    11  	s.add(o);
    12  	if (!s.has(o)) {
    13  		throw new Error("has");
    14  	}
    15  	s.delete(o);
    16  	if (s.has(o)) {
    17  		throw new Error("still has");
    18  	}
    19  	`
    20  	testScript(SCRIPT, _undefined, t)
    21  }
    22  
    23  func TestWeakSetArraySimple(t *testing.T) {
    24  	const SCRIPT = `
    25  	var o1 = {}, o2 = {}, o3 = {};
    26  	
    27  	var s = new WeakSet([o1, o2, o3]);
    28  	s.has(o1) && s.has(o2) && s.has(o3);
    29  	`
    30  	testScript(SCRIPT, valueTrue, t)
    31  }
    32  
    33  func TestWeakSetArrayGeneric(t *testing.T) {
    34  	const SCRIPT = `
    35  	var o1 = {}, o2 = {}, o3 = {};
    36  	var a = new Array();
    37  	var s;
    38  	var thrown = false;
    39  	a[1] = o2;
    40  	
    41  	try {
    42  		s = new WeakSet(a);
    43  	} catch (e) {
    44  		if (e instanceof TypeError) {
    45  			thrown = true;
    46  		}
    47  	}
    48  	if (!thrown) {
    49  		throw new Error("Case 1 does not throw");
    50  	}
    51   
    52  	Object.defineProperty(a.__proto__, "0", {value: o1, writable: true, enumerable: true, configurable: true});
    53  	s = new WeakSet(a);
    54  	if (!(s.has(o1) && s.has(o2) && !s.has(o3))) {
    55  		throw new Error("Case 2 failed");
    56  	}
    57  
    58  	Object.defineProperty(a, "2", {value: o3, configurable: true});	
    59  	s = new WeakSet(a);
    60  	s.has(o1) && s.has(o2) && s.has(o3);
    61  	`
    62  	testScript(SCRIPT, valueTrue, t)
    63  }
    64  
    65  func TestWeakSetGetAdderGetIteratorOrder(t *testing.T) {
    66  	const SCRIPT = `
    67  	let getterCalled = 0;
    68  
    69  	class S extends WeakSet {
    70  	    get add() {
    71  	        getterCalled++;
    72  	        return null;
    73  	    }
    74  	}
    75  
    76  	let getIteratorCalled = 0;
    77  
    78  	let iterable = {};
    79  	iterable[Symbol.iterator] = () => {
    80  	    getIteratorCalled++
    81  	    return {
    82  	        next: 1
    83  	    };
    84  	}
    85  
    86  	let thrown = false;
    87  
    88  	try {
    89  	    new S(iterable);
    90  	} catch (e) {
    91  	    if (e instanceof TypeError) {
    92  	        thrown = true;
    93  	    } else {
    94  	        throw e;
    95  	    }
    96  	}
    97  
    98  	thrown && getterCalled === 1 && getIteratorCalled === 0;
    99  	`
   100  	testScript(SCRIPT, valueTrue, t)
   101  }