SignalR dotnet core MVC Модульное тестирование - PullRequest
0 голосов
/ 08 мая 2018

и простите за запутанный заголовок! поэтому я разрабатываю «лобби», в которое входят пользователи, и другие пользователи могут видеть, когда кто-то входит в него. Лобби может быть много, но только когда пользователь войдет в одно и то же лобби, они появятся. решение и развертывание работают отлично, моя проблема (как следует из названия) тестирование всей этой путаницы! Для этого я решил проверить 2 вещи: 1. Мне нужно проверить правильность вызовов стороны signalR HUB при подключении клиентов и т. Д., Поэтому тестирование серверной части SignalR 2. Мне нужно проверить, что мой javascript, который находится в папке wwwroot / js (asp.net core mvc), для этого мне нужно использовать mocha. Моя проблема здесь в том, что js-файлы находятся в основном проекте c # .net, и я не знаю, как это проверить.

Однако, после неустанного поиска форумов и документов по всей сети, я не нашел решения ни для одной из проблем! Я надеюсь, что кто-то может помочь, возможно, намекнуть на некоторые идеи о том, как я это делаю.

я опубликую свой соответствующий код здесь:


Lobby.cshtml

@using Domain.Interfaces
@using Domain.Models
@using GUI_Index.Session
@using Microsoft.AspNetCore.Http
@model GUI_Index.ViewModels.LobbyViewModel
@{
    ViewData["Title"] = "Tilslut Lobby";
}
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<body>
<div class="container">

    <button id="ForLadLobby" type="button" class="btn btn-post" onclick="location.href = '@Url.Action("ForladLobby", "Lobby", Model)'">Ud af lobby</button>

    <div class="form-group left-Align ingamebox">
        
        <table id="UsersInLobby">
            <th>Users in Lobby: </th>

            @{
                foreach (var usernames in Model.Usernames)
                {
                    <tr id="@usernames">
                        <td>
                            @usernames
                        </td>
                    </tr>
                }
            }
            
        </table>
    </div>

    <div class="form-group right-Align ingamebox">
        Message...<input type="text" id="messageInput" />
        <input type="button" class="btn btn-primary" id="sendButton" value="Send Message" />
    </div>

    @{
        string user = SessionExtension.GetObjectFromJson<User>(Context.Request.HttpContext.Session, "user").Username;
    }

    <form method="post" formaction="@Url.Action("Lobby", "Lobby")">
        <table>
            <tr>
                <div class="top-Align">
                    <div id="center-Text">

                        Hello: <label id="LobbyUser">@user</label>  <br/>
                        Welcome to: <label id="LobbyId">@Model.Id</label>

                    </div>
                        
                    <ul id="Messages"></ul>

                </div>

            </tr>

            <tr>
                <div class="absolute-center is-responsive">
                    <div class="form-group">
                        <input type="hidden" class="form-control" name="Id">
                    </div>
                    <div class="btn-group-vertical">
                        
                        @{
                            if (Model.Admin == user)
                            {
                                <button type="submit" class="btn btn-primary">Start spil</button>
                                <div class="divider"></div>
                                <br />
                            }
                        }

                    </div>
                </div>
            </tr>
        </table>

    </form>

</div>

</body>

<script src='@Url.Content("~/lib/signalr.js")'></script>
<script src='@Url.Content("~/js/Lobby.js")'></script>

Lobbyhub.cs

using System;
using System.Threading.Tasks;
using Domain.Models;
using GUI_Index.Session;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.SignalR;

// https://docs.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api

namespace GUI_Index.Hubs
{
    public class LobbyHub : Hub
    {
        
        //private HttpContext context = new DefaultHttpContext();
        
        /// <summary>
        /// Called by SignalR on connection to page
        /// </summary>
        /// <returns></returns>
        public override async Task OnConnectedAsync()
        {
           await this.Clients.Caller.SendAsync("Connect");
        }


        /// <summary>
        /// called by Lobby.js
        /// </summary>
        /// <param name="username">The username of the user in the lobby</param>
        /// <param name="Lobbyname">The lobbyname of the lobby where user is</param>
        /// <returns></returns>
        public async Task OnConnectedUserAsync(string username, string Lobbyname)
        {
            //add user to group
            await Groups.AddAsync(Context.ConnectionId, Lobbyname);
            
            //send to others in the group
            await this.Clients.OthersInGroup(Lobbyname).SendAsync("onConnectedUser", username);

            //old
            //await this.Clients.Others.SendAsync("OnConnectedUser", username);
        }

        /// <summary>
        /// Called by Lobby.js
        /// </summary>
        /// <param name="user"> the user in the lobby that sends</param>
        /// <param name="LobbyName"> the lobby that the user is in</param>
        /// <param name="message"> the message the user wishes to send</param>
        /// <returns></returns>
        public async Task SendMessageAsync(string user,string LobbyName, string message)
        {
            await this.Clients.Group(LobbyName).SendAsync("ReceiveMessage", user, message);

            //old
            //await this.Clients.All.SendAsync("ReceiveMessage", user, message);

        }

        public async Task UserLeftAsync(string username, string lobbyname)
        {
            await this.Groups.RemoveAsync(Context.ConnectionId, lobbyname);

            await this.Clients.OthersInGroup(lobbyname).SendAsync("OnDisconnectedUser", username);
        }

        /*
        public override async Task OnDisconnectedAsync(Exception exception)
        {
            await this.Clients.All.SendAsync("Disconnect");
        }

        public async Task OnDisconnectedUserAsync(string username)
        {
            await this.Clients.Others.SendAsync("OnDisconnectedUser", username);
        }

        */

    }
}

Lobby.js

const connection = new signalR.HubConnection("/Hubs/LobbyHub", { logger: signalR.LogLevel.Information });

/////////////////////////////////////Enter Lobby///////////////////////////////////////////

connection.on("Connect", () => {

    //get the username
    var Username = document.getElementById("LobbyUser").textContent;
        //get the lobbyName
        var Lobbyname = document.getElementById("LobbyId").textContent;
        //send to hub
        connection.invoke("OnConnectedUserAsync", Username, Lobbyname);
    //}

});



connection.on("OnConnectedUser",
    (user) => {


        if (!document.getElementById(user)) {
            var li = document.createElement("li");
            li.textContent = "User: " + user + " Signed On!";
            document.getElementById("Messages").appendChild(li);

            //update table
            const table = document.getElementById("UsersInLobby");
            const newrow = table.insertRow(table.rows.length);
            //set the id of the row
            newrow.id = user;
            const newcell = newrow.insertCell(0);
            //add user to table
            const newText = document.createTextNode(user);
            newcell.appendChild(newText);
        }

    }); 

///////////////////////////////////////Messages///////////////////////////////////////////////

document.getElementById("sendButton").addEventListener("click", event => {
    //get the username
    const user = document.getElementById("LobbyUser").textContent;
    //get the message 
    const message = document.getElementById("messageInput").value;
    //get the lobbyname
    const lobby = document.getElementById("LobbyId").textContent;
    //send it to hub
        connection.invoke("SendMessageAsync", user,lobby, message).catch(err => console.error);
    event.preventDefault();
});

connection.on("ReceiveMessage", (user, message) => {
    //write the complete message
    const Message = user + " says " + message;
    //create list element
    const li = document.createElement("li");
    //add to list element
    li.textContent = Message;
    //append to chat
    document.getElementById("Messages").appendChild(li);
});

///////////////////////////leave Lobby////////////////////////////////////

//Setup click event
document.getElementById("ForLadLobby").addEventListener("click", event => {
    //get the username
    const user = document.getElementById("LobbyUser").textContent;
    //get the lobbyname
    const lobby = document.getElementById("LobbyId").textContent;
    //send it to hub
    connection.invoke("UserLeftAsync", user, lobby).catch(err => console.error);
    event.preventDefault();
});

//user left
connection.on("OnDisconnectedUser",
    (user) => {
        //create element to hold information
        const li = document.createElement("li");
        //tell others that user left
        li.textContent = "User: " + user + " Signed Off!";
        //add to chat
        document.getElementById("Messages").appendChild(li);

        //update table of online users
        var row = document.getElementById(user);
        //get the table and delete the row!
        row.parentNode.removeChild(row);
        //old
        //row.deleteCell(0);


    });

connection.start().catch(err => console.error);

Надеюсь, вы мне поможете!

...