2017-05-26 78 views
1

我正在编写用户在登录后才能访问的页面的单元测试。我有以下代码来测试用户是否成功登录与否:如何为用户需要登录的网页编写单元测试

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:"[email protected]", 
       password:"admin1" 
      }) 
      .expect('Location','/profile') 
      .end(done); 
     }); 
    }); 

的测试工作,然后我试图添加以下代码:

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

我希望用户应该能够得到秘密页面,但我收到一个错误:

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) 

我试图把第二个“it”函数放到第一个描述块中,我得到了同样的错误。但是当网站正在运行时,用户可以正确访问秘密页面,而不必返回登录页面。

+0

你能发布整个代码吗?请求做了什么?你嘲笑什么? – Ioan

回答

0

您可以尝试调查授权是如何工作的。也许你可以从标题中获取一些标记并稍后使用,只需将正确的标题附加到请求中。

另一种选择可能是使用摩卡的beforeEach()挂钩。