Exemplo n.º 1
0
        public MarkupString RenderComponent(Type componentType)
        {
            var host = new TestHost(_serviceProvider);
            var renderedComponent = host.AddComponent(componentType);

            return((MarkupString)renderedComponent.GetMarkup());
        }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            var host      = new TestHost();
            var component = host.AddComponent <Counter>();

            component.Find("button").Click();
        }
Exemplo n.º 3
0
        public void HtmlStructure_TabComponents()
        {
            var sut = host.AddComponent <TabBarWithSingleTab>();

            var rootNode   = sut.GetDocumentNode();
            var tabElement = rootNode.SelectNodes("/div/div/div/div/button").ShouldHaveSingleItem();

            tabElement.ShouldContainCssClasses("mdc-tab", "mdc-tab--active");
        }
Exemplo n.º 4
0
        public void NewMovie_AllFieldsAreBlank()
        {
            ParameterView paramView = ParameterView.FromDictionary(new Dictionary <string, object>()
            {
                { "movie", new Movie() }, { "IsNewMovie", true }
            });
            var component = host.AddComponent <MovieAddedit>(paramView);

            Assert.Equal("", component.Find("#Title").InnerText);
            Assert.Equal("", component.Find("#Year").InnerText);
            Assert.Equal("", component.Find("#Director").InnerText);
            Assert.Equal("", component.Find("#Description").InnerText);
        }
Exemplo n.º 5
0
        public void DisplaySingleMovie()
        {
            // Arrange
            var movies = GetMovies();

            ParameterView paramView = ParameterView.FromDictionary(new Dictionary <string, object>()
            {
                { "movies", movies.GetRange(0, 1) }
            });
            var component = host.AddComponent <MovieDisplay>(paramView);

            // Assert
            Assert.Equal(movies[0].Title, component.Find(".card-title").InnerText);
            Assert.Equal(movies[0].Year + " - " + movies[0].Director, component.Find(".card-subtitle").InnerText);
            // Must use Contains because of new lines
            Assert.Contains(movies[0].Description, component.Find(".card-text").InnerText);
        }
Exemplo n.º 6
0
        protected ComponentTestBase()
        {
            AllEmployees      = _fixture.CreateMany <Employee>(3).ToList();
            FilteredEmployees = _fixture.CreateMany <Employee>(2).ToList();
            _employeeProvider.GetAll().Returns(AllEmployees);
            _employeeProvider.Filter(Arg.Any <string>(), Arg.Any <Filter>()).Returns(FilteredEmployees);

            _host.AddService(_employeeProvider);
            Component = _host.AddComponent <Index>();
        }
        public void Defaults_Test()
        {
            var layout = host.AddComponent <BsLayout>();

            // default orientiation
            Assert.AreEqual(Orientation.Vertical, layout.Instance.Orientation);

            // default mode
            Assert.AreEqual(EditMode.Editing, layout.Instance.EditMode);
        }
        public async Task ShowConfirmation_ShouldDo()
        {
            var component = _host.AddComponent <Modal>();
            await component.Instance.ShowConfirmation();

            Assert.IsNotNull(component.Find(".show"));
            Assert.AreEqual("Confirmation", component.Find("#exampleModalLabel").InnerHtml);
            Assert.IsTrue(component.Find(".modal").Attributes["style"].Value.Contains("block"));
        }
        public void ShouldRenderTitle()
        {
            var title      = "Test";
            var parameters = new Dictionary <string, object>()
            {
                { "Title", title }
            };
            var component = host.AddComponent <SurveyPrompt>(parameters);

            Assert.Equal(title, component.Find("strong").InnerText);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Render component
        /// </summary>
        /// <param name="host"></param>
        /// <returns></returns>
        public RenderedComponent <TComponent> Render(TestHost host)
        {
            if (host == null)
            {
                throw new ArgumentNullException(nameof(host));
            }
            // create parameters
            var parameters = paramBuilder.ToParameterView();

            // create and return
            return(host.AddComponent <TComponent>(parameters));
        }
Exemplo n.º 11
0
        public void FirstTabIsActive()
        {
            var sut = host.AddComponent <TabBarWithThreeTabs>();

            var rootNode    = sut.GetDocumentNode();
            var tabElements = rootNode.SelectNodes("/div/div/div/div/button");

            tabElements.Count.ShouldBe(3);
            tabElements[0].ShouldContainCssClasses("mdc-tab", "mdc-tab--active");
            tabElements[1].ShouldContainCssClasses("mdc-tab");
            tabElements[2].ShouldContainCssClasses("mdc-tab");
        }
Exemplo n.º 12
0
 public static void CreateTestHost(string userName,
                                   IEnumerable <Claim> claims,
                                   string url,
                                   TestServer sut,
                                   ITestOutputHelper testOutputHelper,
                                   out TestHost host,
                                   out RenderedComponent <blazorApp.App> component,
                                   out MockHttpMessageHandler mockHttp)
 {
     CreateTestHost(userName, claims, url, sut, testOutputHelper, out host, out mockHttp);
     component = host.AddComponent <blazorApp.App>();
 }
Exemplo n.º 13
0
        public void EmptyGroupTest()
        {
            var parameters = new ParameterBuilder()
                             .Add("Label", "a")
                             .ToParameterView();

            var component = host.AddComponent <BsGroup>(parameters);

            // check form group
            var html = component.Find("div").OuterHtml;

            StringAssert.StartsWith(html, "<div class=\"form-group\">");
        }
Exemplo n.º 14
0
        public void EmptyCard_Test()
        {
            var parameters = new ParameterBuilder()
                             .Add("HeaderCss", "a")
                             .ToParameterView();

            var layout = host.AddComponent <BsCard>(parameters);

            // header includes specified css

            // content is empty
            Assert.IsTrue(string.IsNullOrWhiteSpace(layout.Find("div.card-body").InnerText));
        }
Exemplo n.º 15
0
        public void CounterWorks()
        {
            var           component  = host.AddComponent <Counter>();
            Func <string> countValue = () => component.Find("#count").InnerText;

            Assert.Equal("Counter", component.Find("h1").InnerText);
            Assert.Equal("Current count: 0", countValue());

            component.Find("button.inc").Click();
            Assert.Contains("Current count: 1", countValue());

            component.Find("button.dec").Click();
            Assert.Contains("Current count: 0", countValue());
        }
        public void ShouldRenderHello()
        {
            var component = host.AddComponent <BlazorDemo.Pages.Index>();

            // Assert h1
            Assert.Equal("Hello, world!", component.Find("h1").InnerText);
            // Assert text in the body
            Assert.Contains("Welcome to your new app.", component.GetMarkup());
            // Assert if survey component exists
            Assert.NotNull(component.Find(".alert.alert-secondary"));
            // Assert the link
            Assert.Equal(
                "https://go.microsoft.com/fwlink/?linkid=2127212",
                component.Find("a").Attributes["href"].Value);
        }
Exemplo n.º 17
0
        public void SendsSearchCriteria()
        {
            // Arrange
            var app = host.AddComponent <Main>();

            app.Find(".search-from-airport input").Change("JFK");
            app.Find(".search-to-airport input").Change("SYD");
            app.Find(".search-outbound-date input").Change("2020-01-02");
            app.Find(".search-return-date input").Change("2020-03-08");
            app.Find(".search-ticket-class select").Change(TicketClass.First.ToString());
            Assert.Empty(flightDataClient.Calls <SearchCriteria>());

            // Act
            app.Find(".search-submit").Click();
            var call           = flightDataClient.Calls <SearchCriteria>().Single();
            var searchCriteria = call.Request;

            // Assert
            Assert.Equal("JFK", searchCriteria.FromAirport);
            Assert.Equal("SYD", searchCriteria.ToAirport);
            Assert.Equal(new DateTime(2020, 1, 2), searchCriteria.OutboundDate);
            Assert.Equal(new DateTime(2020, 3, 8), searchCriteria.ReturnDate);
            Assert.Equal(TicketClass.First, searchCriteria.TicketClass);
        }
Exemplo n.º 18
0
        public void RadzenButton()
        {
            var component = host.AddComponent <Pages.Index>();

            string RadzenButtonValue() => component.Find("span").InnerText;

            HtmlNode radzenButton = component.Find("button");

            Assert.Equal("Hi!", RadzenButtonValue());

            radzenButton.Click();
            Assert.Equal("Bye", RadzenButtonValue());

            radzenButton.Click();
            Assert.Equal("Hi!", RadzenButtonValue());
        }
Exemplo n.º 19
0
        public void ShouldRenderText()
        {
            TestHost host      = new TestHost();
            var      component = host.AddComponent <FizzBuzz.Pages.Index>();

            // Assert h1
            Assert.Equal("Awesome FizzBuzz in the World!", component.Find("h1").InnerText);
            // Assert text in the body
            Assert.Contains("An example of FizzBuzz using", component.GetMarkup());
            // Assert if survey component exists
            Assert.NotNull(component.Find(".alert.alert-secondary"));
            // Assert the link
            Assert.Equal(
                "awsom_fizzbuzz",
                component.Find("a").Attributes["href"].Value);
        }
Exemplo n.º 20
0
        public void CamperScheduleGrid_ValidSchedule_AllCamperBlocksPopulated(int numberOfActivitiesToVerify)
        {
            // Arrange - run schedule with successful data set
            List <ActivityDefinition> activityDefinitions = new List <ActivityDefinition>(
                _activityDefinitionService.GetActivityDefinition(DefaultSetName));
            List <ActivityDefinition> schedule;

            using (MemoryStream camperRequestStream = new MemoryStream(_validCamperRequestsBuffer))
            {
                List <CamperRequests> camperRequests = CamperRequests.ReadCamperRequests(
                    camperRequestStream, activityDefinitions);
                string scheduleId = "MySchedule";
                schedule = _schedulerService.CreateSchedule(scheduleId, camperRequests, activityDefinitions);
                _localStorage.GetItemAsync <string>(Arg.Any <string>())
                .Returns(Task.FromResult(scheduleId));
            }

            // Act - load the grid component
            RenderedComponent <CamperScheduleGrid> component =
                _host.AddComponent <CamperScheduleGrid>();

            // Assert
            List <HtmlNode> nameCells = component.FindAll("td")
                                        .Where(node => node.Attributes.AttributesWithName("data-name")
                                               .Any(a => a.Value.Equals("FullName"))).ToList();
            int numberOfCampers = 98;

            Assert.That(nameCells, Has.Count.EqualTo(numberOfCampers),
                        "Number of camper rows");

            foreach (var activity in schedule.Take(numberOfActivitiesToVerify))
            {
                for (int timeSlot = 0; timeSlot < ActivityBlock.MaximumTimeSlots; timeSlot++)
                {
                    IActivityBlock activityBlock = activity.ScheduledBlocks.First(
                        ab => ab.TimeSlot == timeSlot);
                    foreach (var camper in activityBlock.AssignedCampers)
                    {
                        string          camperSlotId    = $"{camper.FullName}-{timeSlot}";
                        List <HtmlNode> camperSlotCells = component.FindAll("select")
                                                          .Where(node => node.Attributes.AttributesWithName("id")
                                                                 .Any(a => a.Value.Equals(camperSlotId))).ToList();
                        Assert.That(camperSlotCells, Has.Count.EqualTo(1),
                                    $"Number of camper slots for Id = {camperSlotId}");
                        List <HtmlAttribute> valueAttributes = camperSlotCells[0].Attributes
                                                               .AttributesWithName("value").ToList();
                        Assert.That(valueAttributes, Has.Count.EqualTo(1),
                                    $"Number of value attributes on selector for ID={camperSlotId}");
                        Assert.That(valueAttributes[0].Value,
                                    Is.EqualTo(activity.Name), "Selected activity");
                    }
                }
            }
        }
Exemplo n.º 21
0
        public void Renders_Label_ForPropertyWithDisplayAttributeAndAdditionalAttributes()
        {
            // Arrange
            Expression <Func <string> > For = () => _model.First;
            var parameters = new Dictionary <string, object> {
                { "For", For }, { "class", "c" }
            };

            // Act
            var component = _host.AddComponent <LabelText <string> >(parameters);

            // Assert
            Assert.Equal("<label class=\"c\">my_value</label>", component.Find("label").OuterHtml);

            // Verify
            _stringLocalizerMock.Verify(localizer => localizer["Person_First"], Times.Once);
        }
Exemplo n.º 22
0
        public void Setup()
        {
            IActivityDefinitionService service = Substitute.For <IActivityDefinitionService>();

            service.GetActivitySetNames().Returns(_activitySetNames);
            _host.AddService(service);

            EventCallbackFactory   eventCallbackFactory = new EventCallbackFactory();
            EventCallback <string> eventCallback        = eventCallbackFactory.Create <string>(this, x =>
            {
                _callBackValue = x;
            });
            IDictionary <string, object> parameters = new Dictionary <string, object>
            {
                { "CurrentActivitySetChanged", eventCallback }
            };

            _component = _host.AddComponent <ActivitySetSelector>(parameters);
        }
Exemplo n.º 23
0
        public async Task ToggleNavMenu_should_update_nav_menu_class()
        {
            var navigationInterceptionMock = new Mock <INavigationInterception>();

            using var host = new TestHost();
            host.ConfigureServices(services =>
            {
                services.AddSingleton <NavigationManager, TestNavigationManager>()
                .AddSingleton(p => navigationInterceptionMock.Object);
            });

            var component = host.AddComponent <NavMenu>();

            var div = component.Find("div.collapse");

            Assert.NotNull(div);

            await host.WaitForNextRenderAsync(() => div.ClickAsync());

            Assert.Null(component.Find("div.collapse"));
        }
        public void RunScheduler_InitializeEmptyLocalStorage_ShowDefaultActivitySet()
        {
            // Arrange / Act
            _localStorage.ClearReceivedCalls();
            _localStorage.GetItemAsync <string>(Arg.Any <string>())
            .Returns(Task.FromResult(string.Empty));
            RenderedComponent <RunScheduler> component =
                _host.AddComponent <RunScheduler>();

            // Assert
            // Verify activity set selector is initialized to default
            Assert.That(component.Instance.ActivitySet, Is.EqualTo(DefaultSetName),
                        "ActivitySet initial value");

            // Verify activity set is persisted.
            Received.InOrder(async() =>
            {
                await _localStorage.SetItemAsync(ActivitySetKey, DefaultSetName);
            });
        }
Exemplo n.º 25
0
        public void ShouldRenderCounter()
        {
            var component = host.AddComponent <Counter>();

            Assert.Equal("Counter", component.Find("h1").InnerText);
        }
Exemplo n.º 26
0
        public void AddingComponent_CountIsZero()
        {
            var counter = host.AddComponent <Counter>();

            Assert.Equal("Current count: 0", counter.Find("p").InnerText);
        }
Exemplo n.º 27
0
        private static void NavigateToLoginPage(TestLoggerProvider testLoggerProvider, TestServer server, IServiceScope scope, ConcurrentDictionary <object, object> sessionStore, out HttpClient httpClient, out string redirectUri)
        {
            SeedData.SeedUsers(scope);
            SeedData.SeedConfiguration(scope);

            using var host = new TestHost();
            var jsRuntimeMock = new Mock <IJSRuntime>();
            var navigationInterceptionMock = new Mock <INavigationInterception>();
            var navigationManager          = new TestNavigationManager(uri: "http://exemple.com");

            var client = server.CreateClient();

            httpClient = client;

            host.ConfigureServices(services =>
            {
                blazorApp.Program.ConfigureServices(services);
                services
                .AddLogging(configure =>
                {
                    configure.AddProvider(testLoggerProvider);
                })
                .AddIdentityServer4AdminHttpStores(p => Task.FromResult(client))
                .AddSingleton(p => navigationManager)
                .AddSingleton <NavigationManager>(p => p.GetRequiredService <TestNavigationManager>())
                .AddSingleton(p => jsRuntimeMock.Object)
                .AddSingleton(p => navigationInterceptionMock.Object);
            });

            var httpMock = host.AddMockHttp();

            httpMock.Fallback.Respond(httpClient);
            jsRuntimeMock.Setup(m => m.InvokeAsync <object>("sessionStorage.setItem", It.IsAny <object[]>()))
            .Callback <string, object[]>((_, array) => sessionStore.AddOrUpdate(array[0], array[1], (k, v) => array[1]))
            .ReturnsAsync(null);

            string navigatedUri = null;
            var    waitHandle   = new ManualResetEvent(false);

            navigationManager.OnNavigateToCore = (uri, f) =>
            {
                navigatedUri = uri;
                waitHandle.Set();
            };

            var settingsRequest = httpMock.Capture("/settings.json");
            var component       = host.AddComponent <blazorApp.App>();

            var markup = component.GetMarkup();

            Assert.Contains("Authentication in progress", markup);

            host.WaitForNextRender(() =>
            {
                settingsRequest.SetResult(new
                {
                    ClientId = "theidserveradmin",
                    Scope    = "openid profile theidserveradminapi"
                });
            });

            host.WaitForContains(component, "You are redirecting to the login page. please wait");

            WaitForHttpResponse(waitHandle);

            redirectUri = navigatedUri;
        }
Exemplo n.º 28
0
        private static void OpenLogggedPage(TestLoggerProvider testLoggerProvider, HttpClient httpClient, ConcurrentDictionary <object, object> sessionStore, string location)
        {
            using var host = new TestHost();
            var jsRuntimeMock = new Mock <IJSRuntime>();
            var navigationInterceptionMock = new Mock <INavigationInterception>();
            var navigationManager          = new TestNavigationManager(uri: location);

            host.ConfigureServices(services =>
            {
                blazorApp.Program.ConfigureServices(services);
                services
                .AddLogging(configure =>
                {
                    configure.AddProvider(testLoggerProvider);
                })
                .AddIdentityServer4AdminHttpStores(p => Task.FromResult(httpClient))
                .AddSingleton(p => navigationManager)
                .AddSingleton <NavigationManager>(p => p.GetRequiredService <TestNavigationManager>())
                .AddSingleton(p => jsRuntimeMock.Object)
                .AddSingleton(p => navigationInterceptionMock.Object);
            });

            var httpMock = host.AddMockHttp();

            httpMock.Fallback.Respond(httpClient);

            foreach (var key in sessionStore.Keys)
            {
                jsRuntimeMock.Setup(m => m.InvokeAsync <string>("sessionStorage.getItem", It.Is <object[]>(p => p[0].ToString() == key.ToString())))
                .ReturnsAsync <string, object[], IJSRuntime, string>((_, array) =>
                {
                    if (sessionStore.TryGetValue(array[0], out object value))
                    {
                        return((string)value);
                    }
                    throw new InvalidOperationException($"sessionStore doesn't contain key {key}");
                });
            }

            string navigatedUri = null;
            var    waitHandle   = new ManualResetEvent(false);

            navigationManager.OnNavigateToCore = (uri, f) =>
            {
                navigatedUri = uri;
                waitHandle.Set();
            };

            var settingsRequest = httpMock.Capture("/settings.json");
            var component       = host.AddComponent <blazorApp.App>();

            var markup = component.GetMarkup();

            Assert.Contains("Authentication in progress", markup);

            host.WaitForNextRender(() =>
            {
                settingsRequest.SetResult(new
                {
                    ClientId = "theidserveradmin",
                    Scope    = "openid profile theidserveradminapi"
                });
            });


            WaitForHttpResponse(waitHandle);

            Assert.Equal("http://exemple.com", navigatedUri);
        }
Exemplo n.º 29
0
        public void CountStartsAtZero()
        {
            var component = host.AddComponent <Awesome_FizzBuzz>();

            Assert.Equal("", component.Find("p").InnerText);
        }
Exemplo n.º 30
0
        public void InitiallyDisplaysNoItems()
        {
            var component = host.AddComponent <App>();

            Assert.Empty(component.FindAll(".cart-item"));
        }