Debian Codegraph @

addons/web/static/lib/hoot/tests/core/expect.test.js

raw
1 /** @odoo-module */
2
3 import { describe, expect, makeExpect, test } from "@odoo/hoot";
4 import { check, manuallyDispatchProgrammaticEvent, tick, waitFor } from "@odoo/hoot-dom";
5 import { Component, xml } from "@odoo/owl";
6 import { mountForTest, parseUrl } from "../local_helpers";
7
8 import { Test } from "../../core/test";
9 import { makeLabel } from "../../hoot_utils";
10
11 describe(parseUrl(import.meta.url), () => {
12 test("makeExpect passing, without a test", () => {
13 const [customExpect, hooks] = makeExpect({ headless: true });
14
15 expect(() => customExpect(true).toBe(true)).toThrow(
16 "cannot call `expect()` outside of a test"
17 );
18
19 hooks.before();
20
21 customExpect({ key: true }).toEqual({ key: true });
22 customExpect("oui").toBe("oui");
23
24 const results = hooks.after();
25
26 expect(results.pass).toBe(true);
27 expect(results.events).toHaveLength(2);
28 });
29
30 test("makeExpect failing, without a test", () => {
31 const [customExpect, hooks] = makeExpect({ headless: true });
32
33 hooks.before();
34
35 customExpect({ key: true }).toEqual({ key: true });
36 customExpect("oui").toBe("non");
37
38 const results = hooks.after();
39
40 expect(results.pass).toBe(false);
41 expect(results.events).toHaveLength(2);
42 });
43
44 test("makeExpect with a test", async () => {
45 const [customExpect, hooks] = makeExpect({ headless: true });
46 const customTest = new Test(null, "test", {});
47 customTest.setRunFn(() => {
48 customExpect({ key: true }).toEqual({ key: true });
49 customExpect("oui").toBe("non");
50 });
51
52 hooks.before(customTest);
53
54 await customTest.run();
55
56 const results = hooks.after();
57
58 expect(customTest.lastResults).toBe(results);
59 // Result is expected to have the same shape, no need for other assertions
60 });
61
62 test("makeExpect with a test flagged with TODO", async () => {
63 const [customExpect, hooks] = makeExpect({ headless: true });
64 const customTest = new Test(null, "test", { todo: true });
65 customTest.setRunFn(() => {
66 customExpect(1).toBe(1);
67 });
68
69 hooks.before(customTest);
70
71 await customTest.run();
72
73 const results = hooks.after();
74
75 expect(results.pass).toBe(false);
76 expect(results.events[0].pass).toBe(true);
77 });
78
79 test("makeExpect with no assertions & query events", async () => {
80 await mountForTest(/* xml */ `<div>ABC</div>`);
81
82 const [, hooks] = makeExpect({ headless: true });
83
84 hooks.before();
85
86 await waitFor("div:contains(ABC)");
87
88 const results = hooks.after();
89
90 expect(results.pass).toBe(true);
91 expect(results.events).toHaveLength(1);
92 expect(results.events[0].label).toBe("waitFor");
93 });
94
95 test("makeExpect with no assertions & no query events", () => {
96 const [customExpect, hooks] = makeExpect({ headless: true });
97
98 hooks.before();
99
100 expect(() => customExpect.assertions(0)).toThrow(
101 "expected assertions count should be more than 1"
102 );
103
104 const results = hooks.after();
105
106 expect(results.pass).toBe(false);
107 expect(results.events).toHaveLength(1);
108 expect(results.events[0].message).toEqual([
109 "expected at least",
110 ["1", "integer"],
111 "assertion or query event, but none were run",
112 ]);
113 });
114
115 test("makeExpect with unconsumed matchers", () => {
116 const [customExpect, hooks] = makeExpect({ headless: true });
117
118 hooks.before();
119
120 expect(() => customExpect(true, true)).toThrow("`expect()` only accepts a single argument");
121 customExpect(1).toBe(1);
122 customExpect(true);
123
124 const results = hooks.after();
125
126 expect(results.pass).toBe(false);
127 expect(results.events).toHaveLength(2);
128 expect(results.events[1].message.join(" ")).toBe(
129 "called once without calling any matchers"
130 );
131 });
132
133 test("makeExpect with unverified steps", () => {
134 const [customExpect, hooks] = makeExpect({ headless: true });
135
136 hooks.before();
137
138 customExpect.step("oui");
139 customExpect.verifySteps(["oui"]);
140 customExpect.step("non");
141
142 const results = hooks.after();
143
144 expect(results.pass).toBe(false);
145 expect(results.events).toHaveLength(2); // 1 'verifySteps' + 1 'unverified steps'
146 expect(results.events.at(-1).message).toEqual(["unverified steps"]);
147 });
148
149 test("makeExpect retains current values", () => {
150 const [customExpect, hooks] = makeExpect({ headless: true });
151
152 hooks.before();
153
154 const object = { a: 1 };
155 customExpect(object).toEqual({ b: 2 });
156 object.b = 2;
157
158 const testResult = hooks.after();
159
160 const [assertion] = testResult.events;
161 expect(assertion.pass).toBe(false);
162 expect(assertion.failedDetails[1][1]).toEqual({ a: 1 });
163 expect(object).toEqual({ a: 1, b: 2 });
164 });
165
166 test("'expect' results contain the correct informations", async () => {
167 await mountForTest(/* xml */ `
168 <label style="color: #f00">
169 Checkbox
170 <input class="cb" type="checkbox" />
171 </label>
172 <input type="text" value="abc" />
173 `);
174
175 await check("input[type=checkbox]");
176
177 const [customExpect, hooks] = makeExpect({ headless: true });
178
179 hooks.before();
180
181 const matchers = [
182 // Standard
183 ["toBe", 1, 1],
184 ["toBeCloseTo", 1, 1],
185 ["toBeEmpty", []],
186 ["toBeGreaterThan", 1, 0],
187 ["toBeInstanceOf", {}, Object],
188 ["toBeLessThan", 0, 1],
189 ["toBeOfType", 1, "integer"],
190 ["toBeWithin", 1, 0, 2],
191 ["toEqual", [], []],
192 ["toHaveLength", [], 0],
193 ["toInclude", [1], 1],
194 ["toMatch", "a", "a"],
195 ["toMatchObject", { a: 1, b: { l: [1, 2] } }, { b: { l: [1, 2] } }],
196 [
197 "toThrow",
198 () => {
199 throw new Error("");
200 },
201 ],
202 // DOM
203 ["toBeChecked", ".cb"],
204 ["toBeDisplayed", ".cb"],
205 ["toBeEnabled", ".cb"],
206 ["toBeFocused", ".cb"],
207 ["toBeVisible", ".cb"],
208 ["toHaveAttribute", ".cb", "type", "checkbox"],
209 ["toHaveClass", ".cb", "cb"],
210 ["toHaveCount", ".cb", 1],
211 ["toHaveInnerHTML", ".cb", ""],
212 ["toHaveOuterHTML", ".cb", `<input class="cb" type="checkbox" />`],
213 ["toHaveProperty", ".cb", "checked", true],
214 ["toHaveRect", "label", { x: 0 }],
215 ["toHaveStyle", "label", { color: "rgb(255, 0, 0)" }],
216 ["toHaveText", "label", "Checkbox"],
217 ["toHaveValue", "input[type=text]", "abc"],
218 ];
219
220 for (const [name, ...args] of matchers) {
221 customExpect(args.shift())[name](...args);
222 }
223
224 const testResult = hooks.after();
225
226 expect(testResult.pass).toBe(true);
227 expect(testResult.events).toHaveLength(matchers.length);
228 expect(testResult.events.map(({ label }) => label)).toEqual(matchers.map(([name]) => name));
229 });
230
231 test("'expect' error handling", async () => {
232 const [customExpect, hooks] = makeExpect({ headless: true });
233
234 hooks.before();
235
236 expect(() => customExpect(undefined).toInclude("3")).toThrow(
237 "expected received value to be of type string, any[] or object, got undefined"
238 );
239
240 const testResult = hooks.after();
241
242 expect(testResult.pass).toBe(false);
243 });
244
245 test("assertions are prevented after an error", async () => {
246 const [customExpect, hooks] = makeExpect({ headless: true });
247
248 hooks.before();
249
250 await customExpect(Promise.resolve(1)).resolves.toBe(1);
251 hooks.error(new Error("boom"));
252 customExpect(2).toBe(2);
253 customExpect(Promise.resolve(3)).resolves.toBe(3);
254 await tick();
255
256 const results = hooks.after();
257
258 expect(results.pass).toBe(false);
259 expect(results.events).toHaveLength(3); // toBe + error + unverified errors
260 });
261
262 describe("standard matchers", () => {
263 test("toBe", () => {
264 // Boolean
265 expect(true).toBe(true);
266 expect(true).not.toBe(false);
267
268 // Floats
269 expect(1.1).toBe(1.1);
270 expect(0.1 + 0.2).not.toBe(0.3); // floating point errors
271
272 // Integers
273 expect(+0).toBe(-0);
274 expect(1 + 2).toBe(3);
275 expect(1).not.toBe(-1);
276 expect(NaN).toBe(NaN);
277
278 // Strings
279 expect("abc").toBe("abc");
280 expect(new String("abc")).not.toBe(new String("abc"));
281
282 // Other primitives
283 expect(undefined).toBe(undefined);
284 expect(undefined).not.toBe(null);
285
286 // Symbols
287 const symbol = Symbol("symbol");
288 expect(symbol).toBe(symbol);
289 expect(symbol).not.toBe(Symbol("symbol"));
290 expect(Symbol.for("symbol")).toBe(Symbol.for("symbol"));
291
292 // Objects
293 const object = { x: 1 };
294 expect(object).toBe(object);
295 expect([]).not.toBe([]);
296 expect(object).not.toBe({ x: 1 });
297
298 // Dates
299 const date = new Date(0);
300 expect(date).toBe(date);
301 expect(new Date(0)).not.toBe(new Date(0));
302
303 // Nodes
304 expect(new Image()).not.toBe(new Image());
305 expect(document.createElement("div")).not.toBe(document.createElement("div"));
306 });
307
308 test("toBeCloseTo", () => {
309 expect(0.2 + 0.1).toBeCloseTo(0.3);
310 expect(0.2 + 0.1).toBeCloseTo(0.3, { margin: Number.EPSILON });
311 expect(0.2 + 0.1).not.toBeCloseTo(0.3, { margin: 1e-17 });
312
313 expect(3.51).toBeCloseTo(3);
314 expect(3.51).toBeCloseTo(3.52, { margin: 2e-2 });
315 expect(3.502).not.toBeCloseTo(3.503, { margin: 1e-3 });
316
317 expect(3).toBeCloseTo(4 - 1e-15);
318 expect(3 + 1e-15).toBeCloseTo(4);
319 expect(3).not.toBeCloseTo(4);
320 });
321
322 test("toEqual", () => {
323 // Boolean
324 expect(true).toEqual(true);
325 expect(true).not.toEqual(false);
326
327 // Floats
328 expect(1.1).toEqual(1.1);
329 expect(0.1 + 0.2).not.toEqual(0.3); // floating point errors
330
331 // Integers
332 expect(+0).toEqual(-0);
333 expect(1 + 2).toEqual(3);
334 expect(1).not.toEqual(-1);
335 expect(NaN).toEqual(NaN);
336
337 // Strings
338 expect("abc").toEqual("abc");
339 expect(new String("abc")).toEqual(new String("abc"));
340
341 // Other primitives
342 expect(undefined).toEqual(undefined);
343 expect(undefined).not.toEqual(null);
344
345 // Symbols
346 const symbol = Symbol("symbol");
347 expect(symbol).toEqual(symbol);
348 expect(symbol).not.toEqual(Symbol("symbol"));
349 expect(Symbol.for("symbol")).toEqual(Symbol.for("symbol"));
350
351 // Objects
352 const object = { x: 1 };
353 expect(object).toEqual(object);
354 expect([]).toEqual([]);
355 expect(object).toEqual({ x: 1 });
356
357 // Iterables
358 expect(new Set([1, 4, 6])).toEqual(new Set([1, 4, 6]));
359 expect(new Set([1, 4, 6])).not.toEqual([1, 4, 6]);
360 expect(new Map([[{}, "abc"]])).toEqual(new Map([[{}, "abc"]]));
361
362 // Dates
363 const date = new Date(0);
364 expect(date).toEqual(date);
365 expect(new Date(0)).toEqual(new Date(0));
366
367 // Nodes
368 expect(new Image()).toEqual(new Image());
369 expect(document.createElement("div")).toEqual(document.createElement("div"));
370 expect(document.createElement("div")).not.toEqual(document.createElement("span"));
371 });
372
373 test("toMatch", () => {
374 class Exception extends Error {}
375
376 expect("aaaa").toMatch(/^a{4}$/);
377 expect("aaaa").toMatch("aa");
378 expect("aaaa").not.toMatch("aaaaa");
379
380 // Matcher from a class
381 expect(new Exception("oui")).toMatch(Error);
382 expect(new Exception("oui")).toMatch(Exception);
383 expect(new Exception("oui")).toMatch(new Error("oui"));
384 });
385
386 test("toMatchObject", () => {
387 expect({
388 bath: true,
389 bedrooms: 4,
390 kitchen: {
391 amenities: ["oven", "stove", "washer"],
392 area: 20,
393 wallColor: "white",
394 },
395 }).toMatchObject({
396 bath: true,
397 kitchen: {
398 amenities: ["oven", "stove", "washer"],
399 wallColor: "white",
400 },
401 });
402 expect([{ tralalero: "tralala" }, { foo: 1 }]).toMatchObject([
403 { tralalero: "tralala" },
404 { foo: 1 },
405 ]);
406 expect([{ tralalero: "tralala" }, { foo: 1, lirili: "larila" }]).toMatchObject([
407 { tralalero: "tralala" },
408 { foo: 1 },
409 ]);
410 });
411
412 test("toThrow", async () => {
413 const asyncBoom = async () => {
414 throw new Error("rejection");
415 };
416
417 const boom = () => {
418 throw new Error("error");
419 };
420
421 expect(boom).toThrow();
422 expect(boom).toThrow("error");
423 expect(boom).toThrow(new Error("error"));
424
425 await expect(asyncBoom()).rejects.toThrow();
426 await expect(asyncBoom()).rejects.toThrow("rejection");
427 await expect(asyncBoom()).rejects.toThrow(new Error("rejection"));
428 });
429
430 test("verifyErrors", async () => {
431 expect.assertions(2);
432
433 expect(() => expect.verifyErrors(["event", "promise", "timeout"])).toThrow(
434 "cannot call `expect.verifyErrors()` without calling `expect.errors()` beforehand"
435 );
436
437 expect.errors(3);
438
439 const boom = (msg) => {
440 throw new Error(msg);
441 };
442
443 // Timeout
444 setTimeout(() => boom("timeout"));
445 // Promise
446 queueMicrotask(() => boom("promise"));
447 // Event
448 manuallyDispatchProgrammaticEvent(window, "error", { message: "event" });
449
450 await tick();
451
452 expect.verifyErrors(["event", "promise", "timeout"]);
453 });
454
455 test("verifySteps", () => {
456 expect.assertions(4);
457
458 expect.verifySteps([]);
459
460 expect.step("abc");
461 expect.step("def");
462 expect.verifySteps(["abc", "def"]);
463
464 expect.step({ property: "foo" });
465 expect.step("ghi");
466
467 expect.verifySteps([{ property: "foo" }, "ghi"]);
468 expect.verifySteps([]);
469 });
470 });
471
472 describe("DOM matchers", () => {
473 test("toBeChecked", async () => {
474 await mountForTest(/* xml */ `
475 <input type="checkbox" />
476 <input type="checkbox" checked="" />
477 `);
478
479 expect("input:first").not.toBeChecked();
480 expect("input:last").toBeChecked();
481 });
482
483 test("toHaveAttribute", async () => {
484 await mountForTest(/* xml */ `
485 <input type="number" disabled="" />
486 `);
487
488 expect("input").toHaveAttribute("disabled");
489 expect("input").not.toHaveAttribute("readonly");
490 expect("input").toHaveAttribute("type", "number");
491 });
492
493 test("toHaveCount", async () => {
494 await mountForTest(/* xml */ `
495 <ul>
496 <li>milk</li>
497 <li>eggs</li>
498 <li>milk</li>
499 </ul>
500 `);
501
502 expect("iframe").toHaveCount(0);
503 expect("iframe").not.toHaveCount();
504 expect("ul").toHaveCount(1);
505 expect("ul").toHaveCount();
506 expect("li").toHaveCount(3);
507 expect("li").toHaveCount();
508 expect("li:contains(milk)").toHaveCount(2);
509 });
510
511 test("toHaveProperty", async () => {
512 await mountForTest(/* xml */ `
513 <input type="search" readonly="" />
514 `);
515
516 expect("input").toHaveProperty("type", "search");
517 expect("input").not.toHaveProperty("readonly");
518 expect("input").toHaveProperty("readOnly", true);
519 });
520
521 test("toHaveText", async () => {
522 class TextComponent extends Component {
523 static props = {};
524 static template = xml`
525 <div class="with">With<t t-esc="nbsp" />nbsp</div>
526 <div class="without">Without nbsp</div>
527 `;
528
529 nbsp = "\u00a0";
530 }
531
532 await mountForTest(TextComponent);
533
534 expect(".with").toHaveText("With nbsp");
535 expect(".with").toHaveText("With\u00a0nbsp", { raw: true });
536 expect(".with").not.toHaveText("With\u00a0nbsp");
537
538 expect(".without").toHaveText("Without nbsp");
539 expect(".without").not.toHaveText("Without\u00a0nbsp");
540 expect(".without").not.toHaveText("Without\u00a0nbsp", { raw: true });
541 });
542
543 test("toHaveInnerHTML", async () => {
544 await mountForTest(/* xml */ `
545 <div class="parent">
546 <p>
547 abc<strong>def</strong>ghi
548 <br />
549 <input type="text" />
550 </p>
551 </div>
552 `);
553
554 expect(".parent").toHaveInnerHTML(/* xml */ `
555 <p>abc<strong>def</strong>ghi<br><input type="text"></p>
556 `);
557 });
558
559 test("toHaveOuterHTML", async () => {
560 await mountForTest(/* xml */ `
561 <div class="parent">
562 <p>
563 abc<strong>def</strong>ghi
564 <br />
565 <input type="text" />
566 </p>
567 </div>
568 `);
569
570 expect(".parent").toHaveOuterHTML(/* xml */ `
571 <div class="parent">
572 <p>abc<strong>def</strong>ghi<br><input type="text"></p>
573 </div>
574 `);
575 });
576
577 test("toHaveStyle", async () => {
578 const documentFontSize = parseFloat(
579 getComputedStyle(document.documentElement).fontSize
580 );
581 await mountForTest(/* xml */ `
582 <div class="div" style="width: 3rem; height: 26px" />
583 `);
584
585 expect(".div").toHaveStyle({ width: `${3 * documentFontSize}px`, height: 26 });
586 expect(".div").toHaveStyle({ display: "block" });
587 expect(".div").toHaveStyle("border-top");
588 expect(".div").not.toHaveStyle({ height: 50 });
589
590 expect(".div").toHaveStyle("height: 26px ; width : 3rem", { inline: true });
591 expect(".div").not.toHaveStyle({ display: "block" }, { inline: true });
592 expect(".div").not.toHaveStyle("border-top", { inline: true });
593 });
594
595 test("no elements found messages", async () => {
596 const [customExpect, hooks] = makeExpect({ headless: true });
597 hooks.before();
598
599 await mountForTest(/* xml */ `
600 <div />
601 `);
602
603 const SELECTOR = "#brrbrrpatapim";
604 const DOM_MATCHERS = [
605 ["toBeChecked"],
606 ["toBeDisplayed"],
607 ["toBeEnabled"],
608 ["toBeFocused"],
609 ["toBeVisible"],
610 ["toHaveAttribute", "attr"],
611 ["toHaveClass", "cls"],
612 ["toHaveInnerHTML", "<html></html>"],
613 ["toHaveOuterHTML", "<html></html>"],
614 ["toHaveProperty", "prop"],
615 ["toHaveRect", {}],
616 ["toHaveStyle", {}],
617 ["toHaveText", "abc"],
618 ["toHaveValue", "value"],
619 ];
620
621 for (const [matcher, arg] of DOM_MATCHERS) {
622 customExpect(SELECTOR)[matcher](arg);
623 }
624
625 const results = hooks.after();
626 const assertions = results.getEvents("assertion");
627 for (let i = 0; i < DOM_MATCHERS.length; i++) {
628 const { label, message } = assertions[i];
629 expect.step(label);
630 expect(message).toEqual([
631 "expected at least",
632 makeLabel(1),
633 "element and got",
634 makeLabel(0),
635 "elements matching",
636 makeLabel(SELECTOR),
637 ]);
638 }
639
640 expect.verifySteps(DOM_MATCHERS.map(([matcher]) => matcher));
641 });
642 });
643 });