Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

But what about testing responses in my node application at a specific url? I.e how do I test what response I get from navigating to /users for instance?

Using Expresso, mocha.js's predecessor, I could do assert.response(server, req, res|fn[, msg|fn]) and test the response.

like image 665
Industrial Avatar asked Feb 24 '12 13:02

Industrial


People also ask

What is response in node JS?

The res object represents the HTTP response that an Express app sends when it gets an HTTP request.

Is it possible to write tests in node JS?

Run NodeJS Unit Test using Jest: Example Similarly, multiple Unit test cases can be written for your NodeJS application using Jest.

What is the best testing framework for NodeJS?

What are the best Node. js unit testing frameworks? According to “The State of JavaScript 2021,” the most popular JavaScript testing frameworks and libraries in 2021 were Testing Library, Vitest, Jest, Cypress, Playwright, and Storybook. Rounding out the top ten are Puppeteer, Mocha, Jasmine, AVA, and WebdriverIO.


1 Answers

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.

In short, you run your server code and then actually use either Request or Superagent to make these HTTP requests. I personally prefer Superagent because of it's automatic JSON encoding, but be careful, the docs are out of date and incorrect, YMMV. Most people choose Request.

Simple Mocha Example using Request:

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.

like image 91
JP Richardson Avatar answered Oct 05 '22 03:10

JP Richardson