2017-09-08 64 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)) 

希望這是有幫助:)和抱歉,我不使用分號。