in-operator-basic.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334
  1. test("in operator with objects", () => {
  2. const sym = Symbol();
  3. const o = { foo: "bar", bar: undefined, [sym]: "qux" };
  4. expect("" in o).toBeFalse();
  5. expect("foo" in o).toBeTrue();
  6. expect("bar" in o).toBeTrue();
  7. expect("baz" in o).toBeFalse();
  8. expect("toString" in o).toBeTrue();
  9. expect(sym in o).toBeTrue();
  10. });
  11. test("in operator with arrays", () => {
  12. const a = ["hello", "friends"];
  13. expect(0 in a).toBeTrue();
  14. expect(1 in a).toBeTrue();
  15. expect(2 in a).toBeFalse();
  16. expect("0" in a).toBeTrue();
  17. expect("hello" in a).toBeFalse();
  18. expect("friends" in a).toBeFalse();
  19. expect("length" in a).toBeTrue();
  20. });
  21. test("in operator with string object", () => {
  22. const s = new String("foo");
  23. expect("length" in s).toBeTrue();
  24. });
  25. test("error when used with primitives", () => {
  26. ["foo", 123, null, undefined].forEach(value => {
  27. expect(() => {
  28. "prop" in value;
  29. }).toThrowWithMessage(TypeError, "'in' operator must be used on an object");
  30. });
  31. });