Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Basic Auth in Mocha and SuperTest

I'm trying to set us a test to verify the username and password of a path blocked by the basic auth of a username and password.

it('should receive a status code of 200 with login', function(done) {
    request(url)
        .get("/staging")
        .expect(200)
        .set('Authorization', 'Basic username:password')
        .end(function(err, res) {
            if (err) {
                throw err;
            }

            done();
        });
});
like image 999
Peter Chappy Avatar asked Feb 27 '15 02:02

Peter Chappy


People also ask

How do I run a test on Mocha?

By default, it includes a test command, which doesn't do anything. Replace the value of the test key with your Mocha command (the npx command is no longer necessary): With this change, all you need to execute your tests is to run the npm test command. While this change doesn't save a ton of time now, it helps in other ways.

How do Supertest Mocha and Chai work together to automate tests?

To demonstrate how SuperTest, Mocha, and Chai work together, we'll use these tools to automate a few tests for an application called Airport Gap. The Airport Gap application provides a RESTful API to help others use it to improve their API automation testing skills.

What is Mocha testing framework?

The Mocha testing framework organizes and runs your tests in the way your team prefers, whether its TDD or BDD style. Chai's assertions fit in nicely with Mocha to validate your API responses.

How do I set up Supertest and Mocha in NPM?

First, create a new project inside an empty directory and initialize it by running npm init-y to create a default package.json file. For now, you don't have to edit this file. With the project initialized, you can set up the latest versions of SuperTest, Mocha, and Chai libraries with the following command:


2 Answers

Using the auth method

SuperTest is based on SuperAgent which provides the auth method to facilitate Basic Authentication:

it('should receive a status code of 200 with login', function(done) {
    request(url)
        .get('/staging')
        .auth('the-username', 'the-password')
        .expect(200, done);
});

Source: http://visionmedia.github.io/superagent/#basic-authentication


PS: You can pass done straight to any of the .expect() calls

like image 124
Yves M. Avatar answered Nov 11 '22 16:11

Yves M.


The username:password part must be base64 encoded

You can use something like

.set("Authorization", "basic " + new Buffer("username:password").toString("base64"))
like image 29
pretorh Avatar answered Nov 11 '22 16:11

pretorh