2017-09-08 65 views
0

我正在运行Signin控制器测试,它会一直给出错误的状态代码(401),而不是200,因为我将它编程为。 我希望它使用用户注册时存储的数据,并在给定输入正确的情况下将其返回。 它在邮递员完美的作品,但因为我正在写测试,它会引发401错误。 它就像它没有找到用户Javascript - 在测试期间给出错误的状态代码

这是试块为标志的:

it('it should signin a new user', (done) => { 
     request(app) 
     .post('/api/users/signin') 
     .send({ 
     username: "Charles",   
     password: "challenger",    
     }) 
     .expect(200) 
     .end((err, res) => { 
     if (err) { 
      return done(err); 
     }   

     done() 
     }); 
    }); 

这是在我的日志记录控制器:

signin(req, res) { 

    const username = req.body.username.toLowerCase().trim(); 
    // const email = req.body.email.trim(); 

    if(!username) { 
     return res.status(401) 
     .send(
     {status: false, 
      message: "Username cannot be empty" 
     }); 
    } 
    else if (!req.body.password) { 
     return res.status(401) 
     .send({ 
     status: false, 
     message: "Password field cannot be empty" 
     }); 
    } 
    return User.findOne({ 
     where: { 
     username, 
     } 
    }) 
    .then((user) =>{  

     if(!user) { 
     return res.status(401).send({message: "User is not registered"}) 
     } 
     else if(!user.validPassword(req.body.password)){ 
     return res.status(401) 
     .send({ 
      message: "The password is incorrect" 
     }) 
     } 
     const token = user.generateAuthToken(); 
     res.header('x-auth', token).status(200).send({ 
     statusCode: 200, 
     message: `Welcome back, ${user.username}`, 
     user 
    }); 
    }) 
    .catch(error => {return res.status(400).send(error)}) 
    }, 

这是错误我得到:

1) Testing API routes POST /api/users/ it should signin a new user: 
    Error: expected 200 "OK", got 401 "Unauthorized" 
     at Test._assertStatus (node_modules\supertest\lib\test.js:266: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:1552:8) 
     at _combinedTickCallback (internal/process/next_tick.js:77:11) 
     at process._tickCallback (internal/process/next_tick.js:104:9) 
+0

400是由最后then()子句中某处的javascript错误引起的。尝试在最后的catch块中输出“error”的值,它会告诉你什么失败了。 –

+0

@DuncanThacker对不起,它给出了401错误,而不是400错误。用户可以很好地登录邮递员,但我的测试仍然失败。如果没有用户发生错误 – letmebe

+1

它向401发送哪条消息?这应该有助于确定代码中的哪一部分出错。 –

回答

0

我会把一堆console.log()在里面看看exac TLY该代码是射击,因为你有4次机会触发401

下面是一些代码为你检查:

// I don't understand enough context, so I have to re-write this 
// to show you how it could be an async function which will 
// return a promise, but will also allow you to await. 

// async function sign(req, res) { 
const sign = async (req, res) => { // This is same as above line 

    const username = req.body.username.toLowerCase().trim(); 
    // const email = req.body.email.trim(); 

    if (!username) { 
     console.log('username was empty') 
     return res.status(401).send({ 
      status: false, 
      message: "Username cannot be empty" 
     }); 
    } 

    if (!req.body.password) { 
     console.log('password was empty') 
     return res.status(401).send({ 
      status: false, 
      message: "Password field cannot be empty" 
     }); 
    } 

    return await User.findOne({ where: { username } }) 
     // I'm making this one async also to ensure user.generateAuthToken() 
     // has a value before it proceeds to res.send() 
     .then(async (user) => {  
      if (!user) { 
       console.log('couldnt find user') 
       return res.status(401).send({ 
        message: "User is not registered" 
       }) 
      } 

      else if (!user.validPassword(req.body.password)){ 
       console.log('password was incorrect') 
       return res.status(401).send({ 
        message: "The password is incorrect" 
       }) 
      } 

      const token = await user.generateAuthToken(); 
      // I added a return here 
      return res.header('x-auth', token).status(200).send({ 
       statusCode: 200, 
       message: `Welcome back, ${user.username}`, 
       user 
      }); 
     }) 
     .catch((error) => { 
      console.log('lets put data in here: ' + error) 
      return res.status(400).send(error) 
     }) 
}, 

我注意到MongoDB的搜索User.findOne({ where: { username } })。我不记得它是否需要$where。我认为MongoDB语法使用$。这可能是你的问题,如果是的话,它会触发console.log('couldnt find user')。这可能只适用于本地MongoDB驱动程序。我只是谷歌搜索,并发现语法也可能是:User.findOne({ username })这是User.findOne({ username: username })的简写。

有些人会告诉你,这是多余的做return await fn(),并省略await,但如果承诺被拒绝,它会抛出一个未处理的承诺拒绝。如果在那里等待,它将被捕获。这是上层作用域错误处理体系结构的一部分。

我建议看一些异步/等待教程,因为我看到你在一点回调酱混合。你的代码非常好,但我认为你可以把它提升到一个新的水平。看起来你已经准备好了。

有趣的事实,你也可以省略{}如果您if声明只有一个表情,即:

if (err) { 
    throw err; 
} 

可以简写:

if (err) throw err; 

这可以走很长的路要走帮助清理代码,但使用正确使用try/catch块的异步/等待语法与throw一起使用,将以最小的嵌套对同步代码进行令人难以置信的改进。

这里是你如何能重新写一些这方面,因为我想向您展示我们如何能够摆脱筑巢,增加了混乱的流量控制:

const sign = async (req, res) => { 
    try { 
     const username = req.body.username.toLowerCase().trim() 
     if (!username) throw 'noUsername' 
     if (!req.body.password) throw 'noPassword' 

     const foundUser = await User.findOne({ username }) 
     if (!foundUser.username) throw 'notFound' 

     // I assume this returns Boolean 
     const validPassword = await user.validPassword(req.body.password) 
     if (!validPassword) throw 'invalidPassword' 

     // Alter generateAuthToken() to throw 'badToken' if it fails 
     const token = await user.generateAuthToken() 
     return res.header('x-auth', token).status(200).send({ 
      statusCode: 200, 
      message: `Welcome back, ${user.username}`, 
      user 
     }) 
    } catch (error) { 
     // errors are manually thrown into here, and rejected promises 
     // are automatically thrown into here 
     if (error === 'noUsername') return res.status(401).send({ 
      status: false, 
      message: 'Username cannot be empty' 
     }) 

     if (error === 'noPassword') return res.status(401).send({ 
      status: false, 
      message: 'Password field cannot be empty' 
     }) 

     if (error === 'notFound') return res.status(401).send({ 
      message: 'User is not registered' 
     }) 

     if (error === 'invalidPassword') return res.status(401).send({ 
      message: 'The password is incorrect' 
     }) 

     if (error === 'badToken') return res.status(403).send({ 
      message: 'User is not authorized' 
     }) 

     return res.status(400).send(error) 
    } 
} 

sign(req, res).then((response) => console.log(response)) 

希望这是有帮助:)和抱歉,我不使用分号。