Friday, 26 May 2017

How to write unit test for a web page where user need to log in

I'm writing unit tests for a page that users can only access after they have logged in. I have the following code to test whether the user has successfully logged in or not:

describe('login', function () {
    this.timeout(20000);
    it('should login with correct password', function (done) {
        this.timeout(20000);
        setTimeout(done, 20000);
        request.post('/login')
            .send({
                username:"admin@admin.com",
                password:"admin1"
            })
            .expect('Location','/profile')
            .end(done);
        });
    });

The test works and then I tried to add this code:

describe('secret page',function(){
    it('should get secret',function(done){
        request.get('/secret')
            .expect('Location','/secret')
            .end(done);
    });
});

I expect user should be able to get the secret page but I received an error:

GET /secret 302 0.424 ms - 28
Error: expected "Location" of "/secret", got "/login"
at Test._assertHeader (\node_modules\supertest\lib\test.js:247:12)
at Test._assertFunction (\node_modules\supertest\lib\test.js:281:11)
at Test.assert (\node_modules\supertest\lib\test.js:171:18)
at Server.assert (\node_modules\supertest\lib\test.js:131:12)
at emitCloseNT (net.js:1554:8)
at _combinedTickCallback (internal/process/next_tick.js:77:11)
at process._tickCallback (internal/process/next_tick.js:104:9)

I tried to put the second "it" function into the first describe block, I get the same error. But when the website is running, a user can go to the secret page correctly rather than go back to login page.



via Alan Y.

No comments:

Post a Comment