-
-
Notifications
You must be signed in to change notification settings - Fork 283
Expand file tree
/
Copy pathcontains.test.js
More file actions
78 lines (68 loc) · 2.48 KB
/
contains.test.js
File metadata and controls
78 lines (68 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
const contains = require("./contains.js");
describe("contains", () => {
// Case 1: Should return true if the property exists in object.
test("should return true when object contains passed property name", () => {
const objsWithValidProps = [
[{ a: 1, b: 2 }, "b"],
[{ name: "John", age: 30 }, "name"],
[{ nested: { key: "value" } }, "nested"],
[{ id: 123, status: "active", language: "JavaScript" }, "status"],
[{ data: [], items: null }, "data"],
];
objsWithValidProps.forEach(([obj, prop]) => {
expect(contains(obj, prop)).toEqual(true);
});
});
// Case 2: Should return false if the object does not contain the given property.
test("should return false when object does not contain passed property name", () => {
const objsWithoutProps = [
[{ a: 1, b: 2 }, "c"],
[{ name: "John", age: 30 }, "email"],
[{ nested: { key: "value" } }, "nonexistent"],
[{ id: 123, status: "active", language: "JavaScript" }, "description"],
[{ data: [], items: null }, "nonexistent"],
];
objsWithoutProps.forEach(([obj, prop]) => {
expect(contains(obj, prop)).toEqual(false);
});
});
// Case 3: Should return false if the object is empty.
test("should return false when object is empty", () => {
expect(contains({}, "anyProperty")).toEqual(false);
});
// Case 4: Should return false for properties that only exist in the prototype chain
test("should return false for properties in prototype chain", () => {
const objsWithProtoProps = [
[{ a: 1 }, "toString"],
[{ name: "John", age: 30 }, "hasOwnProperty"],
[{ nested: { key: "value" } }, "isPrototypeOf"],
];
objsWithProtoProps.forEach(([obj, prop]) => {
expect(contains(obj, prop)).toEqual(false);
});
});
// Case 5: Should throw an error if an array is passed
test("should throw error when array is passed", () => {
expect(() => contains(["string"], 0)).toThrow(
"First argument must be an object in the form { key: value }"
);
});
// Case 6: Should throw an error if a non-object is passed
test("should throw error when non-object is passed", () => {
const nonObjects = [
null,
undefined,
42,
"The Curse",
true,
Infinity,
Symbol("sym"),
function () {},
];
nonObjects.forEach((nonObj) => {
expect(() => contains(nonObj, "prop")).toThrow(
"First argument must be an object in the form { key: value }"
);
});
});
});