简体   繁体   English

在node.js中测试响应?

[英]Testing responses in node.js?

I have just downloaded mocha.js and have ran some basic tests with expect.js to ensure that it's working properly. 我刚刚下载了mocha.js并使用expect.js运行了一些基本测试以确保其正常工作。

But what about testing responses in my node application at a specific url? 但是如何在node应用程序中的特定URL上测试响应呢? Ie how do I test what response I get from navigating to /users for instance? 即,如何测试从导航到/users得到的响应?

Using Expresso, mocha.js's predecessor, I could do assert.response(server, req, res|fn[, msg|fn]) and test the response. 使用mocha.js的前身Expresso,我可以做assert.response(server, req, res|fn[, msg|fn])并测试响应。

This is one thing that I love about Node.js/Javascript, doing this sort of thing is simple once you got the hang of it. 这是我喜欢Node.js / Javascript的一件事,一旦掌握了这一点,做这种事情就很简单。

In short, you run your server code and then actually use either Request or Superagent to make these HTTP requests. 简而言之,您运行服务器代码,然后实际使用Request或Superagent发出这些HTTP请求。 I personally prefer Superagent because of it's automatic JSON encoding, but be careful, the docs are out of date and incorrect, YMMV. 我个人更喜欢Superagent,因为它是自动JSON编码,但是请注意,文档过时且不正确,YMMV。 Most people choose Request. 大多数人选择“请求”。

Simple Mocha Example using Request: 使用Request的简单Mocha示例:

describe('My Server', function(){
    describe('GET /users', function(){
        it("should respond with a list of users", function(done){
            request('http://mytesturl.com/users', function(err,resp,body){
                assert(!err);
                myuserlist = JSON.parse(body);
                assert(myuserlist.length, 12); 
                done(); 
            }); 
        }); 
    });
});

Hopefully that helps. 希望有帮助。 Here is a sample of my Mocha (CoffeeScript) testing using this style with complete detailed examples: https://github.com/jprichardson/logmeup-server/blob/develop/test/integration/app.test.coffee Oh ya, it also is using Superagent. 这是我使用这种样式的Mocha(CoffeeScript)测试的示例,并带有完整的详细示例: https : //github.com/jprichardson/logmeup-server/blob/develop/test/integration/app.test.coffee哦,是的也正在使用Superagent。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM