SignalR dotnet核心MVC单元测试

时间:2018-05-08 18:54:24

标签: javascript .net-core signalr signalr-hub signalr.client

抱歉令人困惑的头衔! 所以,我正在开发一个" lobby"用户进入的地方,其他用户可以看到有人登录大厅。可以有很多大厅,但只有当用户登录到同一个大厅时,它们才会显示出来。解决方案和部署工作正常,我的问题是(如标题所示)测试这整个混乱! 为此,我想我需要测试两件事: 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>
&#13;
&#13;
&#13;

Lobbyhub.cs

&#13;
&#13;
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);
        }

        */

    }
}
&#13;
&#13;
&#13;

Lobby.js

&#13;
&#13;
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);
&#13;
&#13;
&#13;

我希望你能帮助我!

0 个答案:

没有答案