-
Notifications
You must be signed in to change notification settings - Fork 10.3k
/
Copy pathRoutingTest.cs
954 lines (766 loc) · 39.5 KB
/
RoutingTest.cs
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Globalization;
using System.Runtime.InteropServices;
using BasicTestApp;
using BasicTestApp.RouterTest;
using Microsoft.AspNetCore.Components.E2ETest.Infrastructure;
using Microsoft.AspNetCore.Components.E2ETest.Infrastructure.ServerFixtures;
using Microsoft.AspNetCore.E2ETesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Interactions;
using Xunit.Abstractions;
namespace Microsoft.AspNetCore.Components.E2ETest.Tests;
public class RoutingTest : ServerTestBase<ToggleExecutionModeServerFixture<Program>>
{
public RoutingTest(
BrowserFixture browserFixture,
ToggleExecutionModeServerFixture<Program> serverFixture,
ITestOutputHelper output)
: base(browserFixture, serverFixture, output)
{
}
protected override void InitializeAsyncCore()
{
Navigate(ServerPathBase, noReload: false);
Browser.WaitUntilTestSelectorReady();
}
[Fact]
public void CanArriveAtDefaultPage()
{
SetUrlViaPushState("/");
var app = Browser.MountTestComponent<TestRouter>();
Assert.Equal("This is the default page.", app.FindElement(By.Id("test-info")).Text);
AssertHighlightedLinks("Default (matches all)", "Default with base-relative URL (matches all)");
}
[Fact]
public void CanArriveAtDefaultPageWithoutTrailingSlash()
{
// This is a bit of a degenerate case because ideally devs would configure their
// servers to enforce a canonical URL (with trailing slash) for the homepage.
// But in case they don't want to, we need to handle it the same as if the URL does
// have a trailing slash.
SetUrlViaPushState("");
var app = Browser.MountTestComponent<TestRouter>();
Assert.Equal("This is the default page.", app.FindElement(By.Id("test-info")).Text);
AssertHighlightedLinks("Default (matches all)", "Default with base-relative URL (matches all)");
}
[Fact]
public void CanArriveAtPageWithParameters()
{
SetUrlViaPushState("/WithParameters/Name/Ghi/LastName/O'Jkl");
var app = Browser.MountTestComponent<TestRouter>();
Assert.Equal("Your full name is Ghi O'Jkl.", app.FindElement(By.Id("test-info")).Text);
AssertHighlightedLinks();
}
[Fact]
public void CanArriveAtPageWithNumberParameters()
{
var testInt = int.MinValue;
var testLong = long.MinValue;
var testDec = -2.33333m;
var testDouble = -1.489d;
var testFloat = -2.666f;
SetUrlViaPushState($"/WithNumberParameters/{testInt}/{testLong}/{testDouble}/{testFloat}/{testDec}");
var app = Browser.MountTestComponent<TestRouter>();
var expected = $"Test parameters: {testInt} {testLong} {testDouble} {testFloat} {testDec}";
Assert.Equal(expected, app.FindElement(By.Id("test-info")).Text);
}
[Fact]
public void CanArriveAtPageWithOptionalParametersProvided()
{
var testAge = 101;
SetUrlViaPushState($"/WithOptionalParameters/{testAge}");
var app = Browser.MountTestComponent<TestRouter>();
var expected = $"Your age is {testAge}.";
Assert.Equal(expected, app.FindElement(By.Id("test-info")).Text);
}
[Fact]
public void CanArriveAtPageWithOptionalParametersNotProvided()
{
SetUrlViaPushState($"/WithOptionalParameters?query=ignored");
var app = Browser.MountTestComponent<TestRouter>();
var expected = $"Your age is .";
Assert.Equal(expected, app.FindElement(By.Id("test-info")).Text);
}
[Fact]
public void CanArriveAtPageWithCatchAllParameter()
{
SetUrlViaPushState("/WithCatchAllParameter/life/the/universe/and/everything%20%3D%2042?query=ignored");
var app = Browser.MountTestComponent<TestRouter>();
var expected = $"The answer: life/the/universe/and/everything = 42.";
Assert.Equal(expected, app.FindElement(By.Id("test-info")).Text);
}
[Fact]
public void CanArriveAtNonDefaultPage()
{
SetUrlViaPushState("/Other");
var app = Browser.MountTestComponent<TestRouter>();
Assert.Equal("This is another page.", app.FindElement(By.Id("test-info")).Text);
AssertHighlightedLinks("Other", "Other with base-relative URL (matches all)");
}
[Fact]
public void CanArriveAtFallbackPageFromBadURI()
{
SetUrlViaPushState("/Oopsie_Daisies%20%This_Aint_A_Real_Page");
var app = Browser.MountTestComponent<TestRouter>();
Assert.Equal("Oops, that component wasn't found!", app.FindElement(By.Id("test-info")).Text);
}
[Fact]
public void CanFollowLinkToOtherPage()
{
SetUrlViaPushState("/");
var app = Browser.MountTestComponent<TestRouter>();
app.FindElement(By.LinkText("Other")).Click();
Browser.Equal("This is another page.", () => app.FindElement(By.Id("test-info")).Text);
AssertHighlightedLinks("Other", "Other with base-relative URL (matches all)");
}
[Fact]
public void CanFollowLinkToOtherPageWithCtrlClick()
{
// On macOS we need to hold the command key not the control for opening a popup
var key = RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? Keys.Command : Keys.Control;
try
{
SetUrlViaPushState("/");
var app = Browser.MountTestComponent<TestRouter>();
var button = app.FindElement(By.LinkText("Other"));
new Actions(Browser).KeyDown(key).Click(button).Build().Perform();
Browser.Equal(2, () => Browser.WindowHandles.Count);
}
finally
{
// Leaving the ctrl key up
new Actions(Browser).KeyUp(key).Build().Perform();
// Closing newly opened windows if a new one was opened
while (Browser.WindowHandles.Count > 1)
{
Browser.SwitchTo().Window(Browser.WindowHandles.Last());
Browser.Close();
}
// Needed otherwise Selenium tries to direct subsequent commands
// to the tab that has already been closed
Browser.SwitchTo().Window(Browser.WindowHandles.First());
}
}
[Fact]
public void CanFollowLinkToTargetBlankClick()
{
try
{
SetUrlViaPushState("/");
var app = Browser.MountTestComponent<TestRouter>();
app.FindElement(By.LinkText("Target (_blank)")).Click();
Browser.Equal(2, () => Browser.WindowHandles.Count);
}
finally
{
// Closing newly opened windows if a new one was opened
while (Browser.WindowHandles.Count > 1)
{
Browser.SwitchTo().Window(Browser.WindowHandles.Last());
Browser.Close();
}
// Needed otherwise Selenium tries to direct subsequent commands
// to the tab that has already been closed
Browser.SwitchTo().Window(Browser.WindowHandles.First());
}
}
[Fact]
public void CanFollowLinkToOtherPageDoesNotOpenNewWindow()
{
SetUrlViaPushState("/");
var app = Browser.MountTestComponent<TestRouter>();
app.FindElement(By.LinkText("Other")).Click();
Assert.Single(Browser.WindowHandles);
}
[Fact]
public void CanFollowLinkToOtherPageWithBaseRelativeUrl()
{
SetUrlViaPushState("/");
var app = Browser.MountTestComponent<TestRouter>();
app.FindElement(By.LinkText("Other with base-relative URL (matches all)")).Click();
Browser.Equal("This is another page.", () => app.FindElement(By.Id("test-info")).Text);
AssertHighlightedLinks("Other", "Other with base-relative URL (matches all)");
}
[Fact]
public void CanFollowLinkToEmptyStringHrefAsBaseRelativeUrl()
{
SetUrlViaPushState("/Other");
var app = Browser.MountTestComponent<TestRouter>();
app.FindElement(By.LinkText("Default with base-relative URL (matches all)")).Click();
Browser.Equal("This is the default page.", () => app.FindElement(By.Id("test-info")).Text);
AssertHighlightedLinks("Default (matches all)", "Default with base-relative URL (matches all)");
}
[Fact]
public void CanFollowLinkToPageWithParameters()
{
SetUrlViaPushState("/Other");
var app = Browser.MountTestComponent<TestRouter>();
app.FindElement(By.LinkText("With parameters")).Click();
Browser.Equal("Your full name is Abc .", () => app.FindElement(By.Id("test-info")).Text);
AssertHighlightedLinks("With parameters");
// Can add more parameters while remaining on same page
app.FindElement(By.LinkText("With more parameters")).Click();
Browser.Equal("Your full name is Abc McDef.", () => app.FindElement(By.Id("test-info")).Text);
AssertHighlightedLinks("With parameters", "With more parameters");
// Can remove parameters while remaining on same page
app.FindElement(By.LinkText("With parameters")).Click();
Browser.Equal("Your full name is Abc .", () => app.FindElement(By.Id("test-info")).Text);
AssertHighlightedLinks("With parameters");
}
[Fact]
public void CanFollowLinkToDefaultPage()
{
SetUrlViaPushState("/Other");
var app = Browser.MountTestComponent<TestRouter>();
app.FindElement(By.LinkText("Default (matches all)")).Click();
Browser.Equal("This is the default page.", () => app.FindElement(By.Id("test-info")).Text);
AssertHighlightedLinks("Default (matches all)", "Default with base-relative URL (matches all)");
}
[Fact]
public void CanFollowLinkToOtherPageWithQueryString()
{
SetUrlViaPushState("/");
var app = Browser.MountTestComponent<TestRouter>();
app.FindElement(By.LinkText("Other with query")).Click();
Browser.Equal("This is another page.", () => app.FindElement(By.Id("test-info")).Text);
AssertHighlightedLinks("Other", "Other with query");
}
[Fact]
public void CanFollowLinkToDefaultPageWithQueryString()
{
SetUrlViaPushState("/Other");
var app = Browser.MountTestComponent<TestRouter>();
app.FindElement(By.LinkText("Default with query")).Click();
Browser.Equal("This is the default page.", () => app.FindElement(By.Id("test-info")).Text);
AssertHighlightedLinks("Default with query");
}
[Fact]
public void CanFollowLinkToOtherPageWithHash()
{
SetUrlViaPushState("/");
var app = Browser.MountTestComponent<TestRouter>();
app.FindElement(By.LinkText("Other with hash")).Click();
Browser.Equal("This is another page.", () => app.FindElement(By.Id("test-info")).Text);
AssertHighlightedLinks("Other", "Other with hash");
}
[Fact]
public void CanFollowLinkToDefaultPageWithHash()
{
SetUrlViaPushState("/Other");
var app = Browser.MountTestComponent<TestRouter>();
app.FindElement(By.LinkText("Default with hash")).Click();
Browser.Equal("This is the default page.", () => app.FindElement(By.Id("test-info")).Text);
AssertHighlightedLinks("Default with hash");
}
[Fact]
public void CanFollowLinkToNotAComponent()
{
SetUrlViaPushState("/");
var app = Browser.MountTestComponent<TestRouter>();
app.FindElement(By.LinkText("Not a component")).Click();
Browser.Equal("Not a component!", () => Browser.Exists(By.Id("test-info")).Text);
}
[Fact]
public void CanFollowLinkDefinedInOpenShadowRoot()
{
SetUrlViaPushState("/");
var app = Browser.MountTestComponent<TestRouter>();
// It's difficult to access elements within a shadow root using Selenium's regular APIs
// Bypass this limitation by clicking the element via JavaScript
var shadowHost = app.FindElement(By.TagName("custom-link-with-shadow-root"));
((IJavaScriptExecutor)Browser).ExecuteScript("arguments[0].shadowRoot.querySelector('a').click()", shadowHost);
Browser.Equal("This is another page.", () => app.FindElement(By.Id("test-info")).Text);
AssertHighlightedLinks("Other", "Other with base-relative URL (matches all)");
}
[Fact]
public void CanGoBackFromNotAComponent()
{
SetUrlViaPushState("/");
// First go to some URL on the router
var app = Browser.MountTestComponent<TestRouter>();
app.FindElement(By.LinkText("Other")).Click();
Browser.True(() => Browser.Url.EndsWith("/Other", StringComparison.Ordinal));
// Now follow a link out of the SPA entirely
app.FindElement(By.LinkText("Not a component")).Click();
Browser.Equal("Not a component!", () => Browser.Exists(By.Id("test-info")).Text);
Browser.True(() => Browser.Url.EndsWith("/NotAComponent.html", StringComparison.Ordinal));
// Now click back
// Because of how the tests are structured with the router not appearing until the router
// tests are selected, we can only observe the test selector being there, but this is enough
// to show we did go back to the right place and the Blazor app started up
Browser.Navigate().Back();
Browser.True(() => Browser.Url.EndsWith("/Other", StringComparison.Ordinal));
Browser.WaitUntilTestSelectorReady();
}
[Fact]
public void CanNavigateProgrammatically()
{
SetUrlViaPushState("/");
var app = Browser.MountTestComponent<TestRouter>();
var testSelector = Browser.WaitUntilTestSelectorReady();
app.FindElement(By.Id("do-navigation")).Click();
Browser.True(() => Browser.Url.EndsWith("/Other", StringComparison.Ordinal));
Browser.Equal("This is another page.", () => app.FindElement(By.Id("test-info")).Text);
AssertHighlightedLinks("Other", "Other with base-relative URL (matches all)");
// Because this was client-side navigation, we didn't lose the state in the test selector
Assert.Equal(typeof(TestRouter).FullName, testSelector.SelectedOption.GetAttribute("value"));
}
[Fact]
public void CanNavigateProgrammaticallyWithForceLoad()
{
SetUrlViaPushState("/");
var app = Browser.MountTestComponent<TestRouter>();
var testSelector = Browser.WaitUntilTestSelectorReady();
app.FindElement(By.Id("do-navigation-forced")).Click();
Browser.True(() => Browser.Url.EndsWith("/Other", StringComparison.Ordinal));
// Because this was a full-page load, our element references should no longer be valid
Assert.Throws<StaleElementReferenceException>(() =>
{
testSelector.SelectedOption.GetAttribute("value");
});
}
[Fact]
public void CanNavigateProgrammaticallyValidateNoReplaceHistoryEntry()
{
// This test checks if default navigation does not replace Browser history entries
SetUrlViaPushState("/");
var app = Browser.MountTestComponent<TestRouter>();
var testSelector = Browser.WaitUntilTestSelectorReady();
app.FindElement(By.LinkText("Programmatic navigation cases")).Click();
Browser.True(() => Browser.Url.EndsWith("/ProgrammaticNavigationCases", StringComparison.Ordinal));
Browser.Contains("programmatic navigation", () => app.FindElement(By.Id("test-info")).Text);
// We navigate to the /Other page
// This will also test our new NavigatTo(string uri) overload (it should not replace the browser history)
app.FindElement(By.Id("do-other-navigation")).Click();
Browser.True(() => Browser.Url.EndsWith("/Other", StringComparison.Ordinal));
AssertHighlightedLinks("Other", "Other with base-relative URL (matches all)");
// After we press back, we should end up at the "/ProgrammaticNavigationCases" page so we know browser history has not been replaced
// If history had been replaced we would have ended up at the "/" page
Browser.Navigate().Back();
Browser.True(() => Browser.Url.EndsWith("/ProgrammaticNavigationCases", StringComparison.Ordinal));
AssertHighlightedLinks("Programmatic navigation cases");
// For completeness, we will test if the normal NavigateTo(string uri, bool forceLoad) overload will also
// NOT change the browser's history. So we basically repeat what we have done above.
app.FindElement(By.Id("do-other-navigation2")).Click();
Browser.True(() => Browser.Url.EndsWith("/Other", StringComparison.Ordinal));
AssertHighlightedLinks("Other", "Other with base-relative URL (matches all)");
Browser.Navigate().Back();
Browser.True(() => Browser.Url.EndsWith("/ProgrammaticNavigationCases", StringComparison.Ordinal));
AssertHighlightedLinks("Programmatic navigation cases");
// Because this was client-side navigation, we didn't lose the state in the test selector
Assert.Equal(typeof(TestRouter).FullName, testSelector.SelectedOption.GetAttribute("value"));
app.FindElement(By.Id("do-other-navigation-forced")).Click();
Browser.True(() => Browser.Url.EndsWith("/Other", StringComparison.Ordinal));
// We check if we had a force load
Assert.Throws<StaleElementReferenceException>(() =>
testSelector.SelectedOption.GetAttribute("value"));
// But still we should be able to navigate back, and end up at the "/ProgrammaticNavigationCases" page
Browser.Navigate().Back();
Browser.True(() => Browser.Url.EndsWith("/ProgrammaticNavigationCases", StringComparison.Ordinal));
Browser.WaitUntilTestSelectorReady();
}
[Fact]
public void CanNavigateProgrammaticallyWithReplaceHistoryEntry()
{
SetUrlViaPushState("/");
var app = Browser.MountTestComponent<TestRouter>();
var testSelector = Browser.WaitUntilTestSelectorReady();
app.FindElement(By.LinkText("Programmatic navigation cases")).Click();
Browser.True(() => Browser.Url.EndsWith("/ProgrammaticNavigationCases", StringComparison.Ordinal));
Browser.Contains("programmatic navigation", () => app.FindElement(By.Id("test-info")).Text);
// We navigate to the /Other page, with "replace" enabled
app.FindElement(By.Id("do-other-navigation-replacehistoryentry")).Click();
Browser.True(() => Browser.Url.EndsWith("/Other", StringComparison.Ordinal));
AssertHighlightedLinks("Other", "Other with base-relative URL (matches all)");
// After we press back, we should end up at the "/" page so we know browser history has been replaced
// If history would not have been replaced we would have ended up at the "/ProgrammaticNavigationCases" page
Browser.Navigate().Back();
Browser.True(() => Browser.Url.EndsWith("/", StringComparison.Ordinal));
AssertHighlightedLinks("Default (matches all)", "Default with base-relative URL (matches all)");
// Because this was all with client-side navigation, we didn't lose the state in the test selector
Assert.Equal(typeof(TestRouter).FullName, testSelector.SelectedOption.GetAttribute("value"));
}
[Fact]
public void CanNavigateProgrammaticallyWithForceLoadAndReplaceHistoryEntry()
{
SetUrlViaPushState("/");
var app = Browser.MountTestComponent<TestRouter>();
var testSelector = Browser.WaitUntilTestSelectorReady();
app.FindElement(By.LinkText("Programmatic navigation cases")).Click();
Browser.True(() => Browser.Url.EndsWith("/ProgrammaticNavigationCases", StringComparison.Ordinal));
Browser.Contains("programmatic navigation", () => app.FindElement(By.Id("test-info")).Text);
// We navigate to the /Other page, with replacehistroyentry and forceload enabled
app.FindElement(By.Id("do-other-navigation-forced-replacehistoryentry")).Click();
Browser.True(() => Browser.Url.EndsWith("/Other", StringComparison.Ordinal));
// We check if we had a force load
Assert.Throws<StaleElementReferenceException>(() =>
testSelector.SelectedOption.GetAttribute("value"));
// After we press back, we should end up at the "/" page so we know browser history has been replaced
Browser.Navigate().Back();
Browser.True(() => Browser.Url.EndsWith("/", StringComparison.Ordinal));
Browser.WaitUntilTestSelectorReady();
}
[Fact]
public void ClickingAnchorWithNoHrefShouldNotNavigate()
{
SetUrlViaPushState("/");
var initialUrl = Browser.Url;
var app = Browser.MountTestComponent<TestRouter>();
app.FindElement(By.Id("anchor-with-no-href")).Click();
Assert.Equal(initialUrl, Browser.Url);
AssertHighlightedLinks("Default (matches all)", "Default with base-relative URL (matches all)");
}
[Fact]
public void UsingNavigationManagerWithoutRouterWorks()
{
var app = Browser.MountTestComponent<NavigationManagerComponent>();
var initialUrl = Browser.Url;
Browser.Equal(Browser.Url, () => app.FindElement(By.Id("test-info")).Text);
var uri = SetUrlViaPushState("/mytestpath");
Browser.Equal(uri, () => app.FindElement(By.Id("test-info")).Text);
var jsExecutor = (IJavaScriptExecutor)Browser;
jsExecutor.ExecuteScript("history.back()");
Browser.Equal(initialUrl, () => app.FindElement(By.Id("test-info")).Text);
}
[Fact]
public void UriHelperCanReadAbsoluteUriIncludingHash()
{
var app = Browser.MountTestComponent<NavigationManagerComponent>();
Browser.Equal(Browser.Url, () => app.FindElement(By.Id("test-info")).Text);
var uri = "/mytestpath?my=query&another#some/hash?tokens";
var expectedAbsoluteUri = $"{_serverFixture.RootUri}subdir{uri}";
SetUrlViaPushState(uri);
Browser.Equal(expectedAbsoluteUri, () => app.FindElement(By.Id("test-info")).Text);
}
[Fact]
public void CanArriveAtRouteWithExtension()
{
// This is an odd test, but it's primarily here to verify routing for routeablecomponentfrompackage isn't available due to
// some unknown reason
SetUrlViaPushState("/Default.html");
var app = Browser.MountTestComponent<TestRouter>();
Assert.Equal("This is the default page.", app.FindElement(By.Id("test-info")).Text);
AssertHighlightedLinks("With extension");
}
[Fact]
public void RoutingToComponentOutsideMainAppDoesNotWork()
{
SetUrlViaPushState("/routeablecomponentfrompackage.html");
var app = Browser.MountTestComponent<TestRouter>();
Assert.Equal("Oops, that component wasn't found!", app.FindElement(By.Id("test-info")).Text);
}
[Fact]
public void RoutingToComponentOutsideMainAppWorksWithAdditionalAssemblySpecified()
{
SetUrlViaPushState("/routeablecomponentfrompackage.html");
var app = Browser.MountTestComponent<TestRouterWithAdditionalAssembly>();
Assert.Contains("This component, including the CSS and image required to produce its", app.FindElement(By.CssSelector("div.special-style")).Text);
}
[Fact]
public void ResetsScrollPositionWhenPerformingInternalNavigation_LinkClick()
{
SetUrlViaPushState("/LongPage1");
var app = Browser.MountTestComponent<TestRouter>();
Browser.Equal("This is a long page you can scroll.", () => app.FindElement(By.Id("test-info")).Text);
BrowserScrollY = 500;
Browser.True(() => BrowserScrollY > 300); // Exact position doesn't matter
app.FindElement(By.LinkText("Long page 2")).Click();
Browser.Equal("This is another long page you can scroll.", () => app.FindElement(By.Id("test-info")).Text);
Browser.Equal(0, () => BrowserScrollY);
}
[Fact]
public void ResetsScrollPositionWhenPerformingInternalNavigation_ProgrammaticNavigation()
{
SetUrlViaPushState("/LongPage1");
var app = Browser.MountTestComponent<TestRouter>();
Browser.Equal("This is a long page you can scroll.", () => app.FindElement(By.Id("test-info")).Text);
BrowserScrollY = 500;
Browser.True(() => BrowserScrollY > 300); // Exact position doesn't matter
app.FindElement(By.Id("go-to-longpage2")).Click();
Browser.Equal("This is another long page you can scroll.", () => app.FindElement(By.Id("test-info")).Text);
Browser.Equal(0, () => BrowserScrollY);
}
[Fact]
public void PreventDefault_CanBlockNavigation_ForInternalNavigation_PreventDefaultTarget()
=> PreventDefault_CanBlockNavigation("internal", "target");
[Fact]
public void PreventDefault_CanBlockNavigation_ForExternalNavigation_PreventDefaultAncestor()
=> PreventDefault_CanBlockNavigation("external", "ancestor");
[Theory]
[InlineData("external", "target")]
[InlineData("external", "descendant")]
[InlineData("internal", "ancestor")]
[InlineData("internal", "descendant")]
public virtual void PreventDefault_CanBlockNavigation(string navigationType, string whereToPreventDefault)
{
SetUrlViaPushState("/PreventDefaultCases");
var app = Browser.MountTestComponent<TestRouter>();
var preventDefaultToggle = app.FindElement(By.CssSelector($".prevent-default .{whereToPreventDefault}"));
var linkElement = app.FindElement(By.Id($"{navigationType}-navigation"));
var counterButton = app.FindElement(By.ClassName("counter-button"));
if (whereToPreventDefault == "descendant")
{
// We're testing clicks on the link's descendant element
linkElement = linkElement.FindElement(By.TagName("span"));
}
// If preventDefault is on, then navigation does not occur
preventDefaultToggle.Click();
linkElement.Click();
// We check that no navigation ocurred by observing that we can still use the counter
counterButton.Click();
Browser.Equal("Counter: 1", () => counterButton.Text);
// Now if we toggle preventDefault back off, then navigation will occur
preventDefaultToggle.Click();
linkElement.Click();
if (navigationType == "external")
{
Browser.Equal("about:blank", () => Browser.Url);
}
else
{
Browser.Equal("This is another page.", () => app.FindElement(By.Id("test-info")).Text);
AssertHighlightedLinks("Other", "Other with base-relative URL (matches all)");
}
}
[Fact]
public void OnNavigate_CanRenderLoadingFragment()
{
var app = Browser.MountTestComponent<TestRouterWithOnNavigate>();
SetUrlViaPushState("/LongPage1");
Browser.Exists(By.Id("loading-banner"));
}
[Fact]
public void OnNavigate_CanCancelCallback()
{
var app = Browser.MountTestComponent<TestRouterWithOnNavigate>();
// Navigating from one page to another should
// cancel the previous OnNavigate Task
SetUrlViaPushState("/LongPage2");
SetUrlViaPushState("/LongPage1");
AssertDidNotLog("I'm not happening...");
}
[Fact]
public void OnNavigate_CanRenderUIForExceptions()
{
var app = Browser.MountTestComponent<TestRouterWithOnNavigate>();
SetUrlViaPushState("/Other");
var errorUiElem = Browser.Exists(By.Id("blazor-error-ui"), TimeSpan.FromSeconds(10));
Assert.NotNull(errorUiElem);
}
[Fact]
public void OnNavigate_CanRenderUIForSyncExceptions()
{
var app = Browser.MountTestComponent<TestRouterWithOnNavigate>();
// Should capture exception from synchronously thrown
SetUrlViaPushState("/WithLazyAssembly");
var errorUiElem = Browser.Exists(By.Id("blazor-error-ui"), TimeSpan.FromSeconds(10));
Assert.NotNull(errorUiElem);
}
[Fact]
public void OnNavigate_DoesNotRenderWhileOnNavigateExecuting()
{
var app = Browser.MountTestComponent<TestRouterWithOnNavigate>();
// Navigate to a route
SetUrlViaPushState("/WithParameters/name/Abc");
// Click the button to trigger a re-render
var button = app.FindElement(By.Id("trigger-rerender"));
button.Click();
// Assert that the parameter route didn't render
Browser.DoesNotExist(By.Id("test-info"));
// Navigate to another page to cancel the previous `OnNavigateAsync`
// task and trigger a re-render on its completion
SetUrlViaPushState("/LongPage1");
// Confirm that the route was rendered
Browser.Equal("This is a long page you can scroll.", () => app.FindElement(By.Id("test-info")).Text);
}
[Theory]
[InlineData("/WithParameters/Name/Ñoño ñi/LastName/O'Jkl")]
[InlineData("/WithParameters/Name/[Ñoño ñi]/LastName/O'Jkl")]
[InlineData("/other?abc=Ñoño ñi")]
[InlineData("/other?abc=[Ñoño ñi]")]
public void CanArriveAtPageWithSpecialURL(string relativeUrl)
{
SetUrlViaPushState(relativeUrl, true);
var errorUi = Browser.Exists(By.Id("blazor-error-ui"));
Browser.Equal("none", () => errorUi.GetCssValue("display"));
}
[Fact]
public void FocusOnNavigation_SetsFocusToMatchingElement()
{
// Applies focus on initial load
SetUrlViaPushState("/");
var app = Browser.MountTestComponent<TestRouter>();
Browser.True(() => GetFocusedElement().Text == "This is the default page.");
// Updates focus after navigation to regular page
app.FindElement(By.LinkText("Other")).Click();
Browser.True(() => GetFocusedElement().Text == "This is another page.");
// If there's no matching element, we leave the focus unchanged
app.FindElement(By.Id("with-lazy-assembly")).Click();
Browser.Exists(By.Id("use-package-button"));
Browser.Equal("a", () => GetFocusedElement().TagName);
// No errors from lack of matching element - app still functions
app.FindElement(By.LinkText("Other")).Click();
Browser.True(() => GetFocusedElement().Text == "This is another page.");
IWebElement GetFocusedElement()
=> Browser.SwitchTo().ActiveElement();
}
[Fact]
public void CanArriveAtQueryStringPageWithNoQuery()
{
SetUrlViaPushState("/WithQueryParameters/Abc");
var app = Browser.MountTestComponent<TestRouter>();
Assert.Equal("Hello Abc .", app.FindElement(By.Id("test-info")).Text);
Assert.Equal("0", app.FindElement(By.Id("value-QueryInt")).Text);
Assert.Equal(string.Empty, app.FindElement(By.Id("value-NullableDateTimeValue")).Text);
Assert.Equal(string.Empty, app.FindElement(By.Id("value-NullableDateOnlyValue")).Text);
Assert.Equal(string.Empty, app.FindElement(By.Id("value-NullableTimeOnlyValue")).Text);
Assert.Equal(string.Empty, app.FindElement(By.Id("value-StringValue")).Text);
Assert.Equal("0 values ()", app.FindElement(By.Id("value-LongValues")).Text);
AssertHighlightedLinks("With query parameters (none)");
}
[Fact]
public void CanArriveAtQueryStringPageWithStringQuery()
{
SetUrlViaPushState("/WithQueryParameters/Abc?stringvalue=Hello+there#123");
var app = Browser.MountTestComponent<TestRouter>();
Assert.Equal("Hello Abc .", app.FindElement(By.Id("test-info")).Text);
Assert.Equal("0", app.FindElement(By.Id("value-QueryInt")).Text);
Assert.Equal(string.Empty, app.FindElement(By.Id("value-NullableDateTimeValue")).Text);
Assert.Equal(string.Empty, app.FindElement(By.Id("value-NullableDateOnlyValue")).Text);
Assert.Equal(string.Empty, app.FindElement(By.Id("value-NullableTimeOnlyValue")).Text);
Assert.Equal("Hello there", app.FindElement(By.Id("value-StringValue")).Text);
Assert.Equal("0 values ()", app.FindElement(By.Id("value-LongValues")).Text);
AssertHighlightedLinks("With query parameters (none)", "With query parameters (passing string value)");
}
[Fact]
public void CanArriveAtQueryStringPageWithDateTimeQuery()
{
var dateTime = new DateTime(2000, 1, 2, 3, 4, 5, 6);
var dateOnly = new DateOnly(2000, 1, 2);
var timeOnly = new TimeOnly(3, 4, 5, 6);
SetUrlViaPushState($"/WithQueryParameters/Abc?NullableDateTimeValue=2000-01-02%2003:04:05&NullableDateOnlyValue=2000-01-02&NullableTimeOnlyValue=03:04:05");
var app = Browser.MountTestComponent<TestRouter>();
Assert.Equal("Hello Abc .", app.FindElement(By.Id("test-info")).Text);
Assert.Equal("0", app.FindElement(By.Id("value-QueryInt")).Text);
Assert.Equal(dateTime.ToString("hh:mm:ss on yyyy-MM-dd", CultureInfo.InvariantCulture), app.FindElement(By.Id("value-NullableDateTimeValue")).Text);
Assert.Equal(dateOnly.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture), app.FindElement(By.Id("value-NullableDateOnlyValue")).Text);
Assert.Equal(timeOnly.ToString("hh:mm:ss", CultureInfo.InvariantCulture), app.FindElement(By.Id("value-NullableTimeOnlyValue")).Text);
Assert.Equal(string.Empty, app.FindElement(By.Id("value-StringValue")).Text);
Assert.Equal("0 values ()", app.FindElement(By.Id("value-LongValues")).Text);
AssertHighlightedLinks("With query parameters (none)", "With query parameters (passing Date Time values)");
}
[Fact]
public void CanNavigateToQueryStringPageWithNoQuery()
{
SetUrlViaPushState("/");
var app = Browser.MountTestComponent<TestRouter>();
app.FindElement(By.LinkText("With query parameters (none)")).Click();
Assert.Equal("Hello Abc .", app.FindElement(By.Id("test-info")).Text);
Assert.Equal("0", app.FindElement(By.Id("value-QueryInt")).Text);
Assert.Equal(string.Empty, app.FindElement(By.Id("value-NullableDateTimeValue")).Text);
Assert.Equal(string.Empty, app.FindElement(By.Id("value-NullableDateOnlyValue")).Text);
Assert.Equal(string.Empty, app.FindElement(By.Id("value-NullableTimeOnlyValue")).Text);
Assert.Equal(string.Empty, app.FindElement(By.Id("value-StringValue")).Text);
Assert.Equal("0 values ()", app.FindElement(By.Id("value-LongValues")).Text);
AssertHighlightedLinks("With query parameters (none)");
}
[Fact]
public void CanNavigateBetweenPagesWithQueryStrings()
{
SetUrlViaPushState("/");
// Navigate to a page with querystring
var app = Browser.MountTestComponent<TestRouter>();
app.FindElement(By.LinkText("With query parameters (passing string value)")).Click();
Browser.Equal("Hello Abc .", () => app.FindElement(By.Id("test-info")).Text);
Assert.Equal("0", app.FindElement(By.Id("value-QueryInt")).Text);
Assert.Equal(string.Empty, app.FindElement(By.Id("value-NullableDateTimeValue")).Text);
Assert.Equal(string.Empty, app.FindElement(By.Id("value-NullableDateOnlyValue")).Text);
Assert.Equal(string.Empty, app.FindElement(By.Id("value-NullableTimeOnlyValue")).Text);
Assert.Equal("Hello there", app.FindElement(By.Id("value-StringValue")).Text);
Assert.Equal("0 values ()", app.FindElement(By.Id("value-LongValues")).Text);
var instanceId = app.FindElement(By.Id("instance-id")).Text;
Assert.True(!string.IsNullOrWhiteSpace(instanceId));
AssertHighlightedLinks("With query parameters (none)", "With query parameters (passing string value)");
// We can also navigate to a different query while retaining the same component instance
app.FindElement(By.LinkText("With IntValue and LongValues")).Click();
Browser.Equal("123", () => app.FindElement(By.Id("value-QueryInt")).Text);
Assert.Equal(string.Empty, app.FindElement(By.Id("value-NullableDateTimeValue")).Text);
Assert.Equal(string.Empty, app.FindElement(By.Id("value-NullableDateOnlyValue")).Text);
Assert.Equal(string.Empty, app.FindElement(By.Id("value-NullableTimeOnlyValue")).Text);
Assert.Equal(string.Empty, app.FindElement(By.Id("value-StringValue")).Text);
Assert.Equal("3 values (50, 100, -20)", app.FindElement(By.Id("value-LongValues")).Text);
Assert.Equal(instanceId, app.FindElement(By.Id("instance-id")).Text);
AssertHighlightedLinks("With query parameters (none)");
// We can also click back to go the preceding query while retaining the same component instance
Browser.Navigate().Back();
Browser.Equal("0", () => app.FindElement(By.Id("value-QueryInt")).Text);
Assert.Equal(string.Empty, app.FindElement(By.Id("value-NullableDateTimeValue")).Text);
Assert.Equal(string.Empty, app.FindElement(By.Id("value-NullableDateOnlyValue")).Text);
Assert.Equal(string.Empty, app.FindElement(By.Id("value-NullableTimeOnlyValue")).Text);
Assert.Equal("Hello there", app.FindElement(By.Id("value-StringValue")).Text);
Assert.Equal("0 values ()", app.FindElement(By.Id("value-LongValues")).Text);
Assert.Equal(instanceId, app.FindElement(By.Id("instance-id")).Text);
AssertHighlightedLinks("With query parameters (none)", "With query parameters (passing string value)");
}
[Fact]
public void IgnoresQueryString()
{
SetUrlViaPushState("/WithQueryParameters/IgnoreQueryString?intvalue=123");
var app = Browser.MountTestComponent<TestRouter>();
Assert.Equal("123", app.FindElement(By.Id("value-QueryInt")).Text);
AssertHighlightedLinks("Base IgnoreQueryString URL");
}
[Fact]
public void IgnoresQueryStringWithTrailingSlash()
{
SetUrlViaPushState("/WithQueryParameters/IgnoreQueryString/?intvalue=123");
var app = Browser.MountTestComponent<TestRouter>();
Assert.Equal("123", app.FindElement(By.Id("value-QueryInt")).Text);
AssertHighlightedLinks("Base IgnoreQueryString URL");
}
[Fact]
public void DoesNotIgnoreQueryString()
{
SetUrlViaPushState("/WithQueryParameters/DoNotIgnoreQueryString?intvalue=123");
var app = Browser.MountTestComponent<TestRouter>();
Assert.Equal("123", app.FindElement(By.Id("value-QueryInt")).Text);
AssertHighlightedLinks("With query parameters (matches all and does not ignore query string)");
}
[Fact]
public void DoesNotIgnoreQueryStringWithTrailingSlash()
{
SetUrlViaPushState("/WithQueryParameters/DoNotIgnoreQueryString/?intvalue=123");
var app = Browser.MountTestComponent<TestRouter>();
Assert.Equal("123", app.FindElement(By.Id("value-QueryInt")).Text);
AssertHighlightedLinks("With query parameters (matches all and does not ignore query string with trailing slash)");
}
private long BrowserScrollY
{
get => (long)((IJavaScriptExecutor)Browser).ExecuteScript("return window.scrollY");
set => ((IJavaScriptExecutor)Browser).ExecuteScript($"window.scrollTo(0, {value})");
}
private string SetUrlViaPushState(string relativeUri, bool forceLoad = false)
{
var pathBaseWithoutHash = ServerPathBase.Split('#')[0];
var jsExecutor = (IJavaScriptExecutor)Browser;
var absoluteUri = new Uri(_serverFixture.RootUri, $"{pathBaseWithoutHash}{relativeUri}");
jsExecutor.ExecuteScript($"Blazor.navigateTo('{absoluteUri.ToString().Replace("'", "\\'")}', {(forceLoad ? "true" : "false")})");
return absoluteUri.AbsoluteUri;
}
private void AssertDidNotLog(params string[] messages)
{
var log = Browser.Manage().Logs.GetLog(LogType.Browser);
foreach (var message in messages)
{
Assert.DoesNotContain(log, entry => entry.Message.Contains(message));
}
}
private void AssertHighlightedLinks(params string[] linkTexts)
{
Browser.Equal(linkTexts, () => Browser
.FindElements(By.CssSelector("a.active"))
.Select(x => x.Text));
}
}