如何单元测试javascript客户端身份验证

时间:2013-10-15 14:33:24

标签: javascript unit-testing authentication tdd

我正在努力改进单元测试(并希望自己教TDD)。我目前的项目是Javascript,我是新手。我想知道如何对我的身份验证进行单元测试?我想我可能不得不制作一个模拟服务器来代替我实际要进行身份验证的服务器,但我不知道如何去做。

如果测试框架对答案很重要,我一直在尝试使用JSTestDriver - 尽管如果用其他东西更容易我会开放学习,因为我没有花很多时间投入到特定的框架。

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

在这里测试整个系统有点过于宽泛,但我可以解决有关使用模拟服务器的部分。

Sinon.JS,一个测试双库,有一个假的XHR /服务器,非常适合模拟响应。

docs的这个示例中,我们在安装过程中初始化虚假服务器并在拆卸时将其删除。然后我们告诉服务器使用server.respondWith()返回哪些数据。

getCommentsFor()正常进行的服务器调用被假服务器拦截,并使用respondWith()提供我们在测试中提供的数据。通过调用server.respond(),可以立即执行虚假服务器调用,这意味着我们不必考虑正常的异步操作。

{
    setUp: function () {
        this.server = sinon.fakeServer.create();
    },

    tearDown: function () {
        this.server.restore();
    },

    "test should fetch comments from server" : function () {
        this.server.respondWith("GET", "/some/article/comments.json",
                                [200, { "Content-Type": "application/json" },
                                 '[{ "id": 12, "comment": "Hey there" }]']);

        var callback = sinon.spy();
        myLib.getCommentsFor("/some/article", callback);
        this.server.respond();

        sinon.assert.calledWith(callback, [{ id: 12, comment: "Hey there" }]));
    }
}