blob: 6691bd815bbdf7516700f20e97b768af90fd697c [file] [log] [blame]
Ben Rohlfs1da030b2023-01-31 13:09:53 +01001/**
2 * @license
3 * Copyright 2023 Google LLC
4 * SPDX-License-Identifier: Apache-2.0
5 */
6import '../../../test/common-test-setup';
7import {html, assert, fixture, waitUntil} from '@open-wc/testing';
8import './gr-router';
9import {Page, PageContext} from './gr-page';
10
11suite('gr-page tests', () => {
12 let page: Page;
13
14 setup(() => {
15 page = new Page();
16 page.start({dispatch: false, popstate: false, base: ''});
17 });
18
19 teardown(() => {
20 page.stop();
21 });
22
23 test('click handler', async () => {
24 const spy = sinon.spy();
25 page.registerRoute(/\/settings/, spy);
26 const link = await fixture<HTMLAnchorElement>(
27 html`<a href="/settings"></a>`
28 );
29 link.click();
30 assert.isTrue(spy.calledOnce);
31 });
32
33 test('register route and exit', () => {
34 const handleA = sinon.spy();
35 const handleAExit = sinon.stub();
36 page.registerRoute(/\/A/, handleA);
37 page.registerExitRoute(/\/A/, handleAExit);
38
39 page.show('/A');
40 assert.equal(handleA.callCount, 1);
41 assert.equal(handleAExit.callCount, 0);
42
43 page.show('/B');
44 assert.equal(handleA.callCount, 1);
45 assert.equal(handleAExit.callCount, 1);
46 });
47
48 test('register, show, replace', () => {
49 const handleA = sinon.spy();
50 const handleB = sinon.stub();
51 page.registerRoute(/\/A/, handleA);
52 page.registerRoute(/\/B/, handleB);
53
54 page.show('/A');
55 assert.equal(handleA.callCount, 1);
56 assert.equal(handleB.callCount, 0);
57
58 page.show('/B');
59 assert.equal(handleA.callCount, 1);
60 assert.equal(handleB.callCount, 1);
61
62 page.replace('/A');
63 assert.equal(handleA.callCount, 2);
64 assert.equal(handleB.callCount, 1);
65
66 page.replace('/B');
67 assert.equal(handleA.callCount, 2);
68 assert.equal(handleB.callCount, 2);
69 });
70
71 test('register pattern, check context', async () => {
72 let context: PageContext;
73 const handler = (ctx: PageContext) => (context = ctx);
74 page.registerRoute(/\/asdf\/(.*)\/qwer\/(.*)\//, handler);
75 page.stop();
76 page.start({dispatch: false, popstate: false, base: '/base'});
77
78 page.show('/base/asdf/1234/qwer/abcd/');
79
80 await waitUntil(() => !!context);
81 assert.equal(context!.canonicalPath, '/base/asdf/1234/qwer/abcd/');
82 assert.equal(context!.path, '/asdf/1234/qwer/abcd/');
83 assert.equal(context!.querystring, '');
84 assert.equal(context!.hash, '');
85 assert.equal(context!.params[0], '1234');
86 assert.equal(context!.params[1], 'abcd');
87
88 page.show('/asdf//qwer////?a=b#go');
89
90 await waitUntil(() => !!context);
91 assert.equal(context!.canonicalPath, '/base/asdf//qwer////?a=b#go');
92 assert.equal(context!.path, '/asdf//qwer////?a=b');
93 assert.equal(context!.querystring, 'a=b');
94 assert.equal(context!.hash, 'go');
95 assert.equal(context!.params[0], '');
96 assert.equal(context!.params[1], '//');
97 });
98});