【问题标题】:How to change const values while testing with Jest使用 Jest 进行测试时如何更改 const 值
【发布时间】:2020-07-03 05:43:15
【问题描述】:

您好,我正在为我的 node.js API 编写测试,但遇到了问题。我正在使用“const = emailCount”验证我的代码中是否存在电子邮件。如果确实存在,则返回错误 JSON。如果它不存在,它会返回一个成功的 JSON。但是我不确定如何模拟我在代码中声明的内部常量。

代码如下:

    async function registerUser(req, res) {
       // Request
      const email = req.body.email;
      const password = req.body.password;
      const firstName = req.body.firstName;
      const lastName = req.body.lastName;
      const inviteCode = req.body.inviteCode;
      let errMessage = [];
 if (!firstName) {
    errMessage.push("first Name Required")
}

if (!lastName) {
    errMessage.push("last Name Required")
}
if (!inviteCode) {
    errMessage.push("inviteCode Required")
}
if (!email) {
    errMessage.push("email Required")
}
if (!password) {
    errMessage.push("password Required")
}

if (errMessage.length > 0) {
    res.json({ code: "422", message: errMessage })
}

const accessToken = jwt.sign({
    email: email,
    firstName: firstName,
    lastName: lastName
}, config.jwtSecret);

const emailCount = await db.doesEmailExists(email)

if (emailCount.doesEmailExists > 0) {
    res.json({ Errors: "Account already exists" })
} else {
    db.createUser({
        username: email,
        hashedPassword: password,
        firstName: firstName,
        lastName: lastName,
    }).then(data => {
        res.json({
            id: data.insertId,
            firstName: firstName,
            lastName: lastName,
            token: accessToken,
            role: 'user'
        })
    }).catch(err => res.json({ Error: err }))
}

}

这是我的测试代码

  test('POST /user/register', async () => {
     //use super test to send post method with json payload of newUser
     const res = await agent.post('/user/register').send(newUser);


     expect(res.statusCode).toEqual(200) 
     expect(res.body).toHaveProperty('Errors') || expect(res.body).toHaveProperty('token');
  })

如果可能的话,我最终想在我的测试中更改 emailCount 的值,以便在有用户和没有用户的情况下测试不同的响应。

【问题讨论】:

    标签: node.js api express jestjs supertest


    【解决方案1】:

    您不应该模拟您的代码,而应该模拟您的依赖项,db 就是这样。

    例如,您可以这样编写测试场景:

    const db = require('./path/to/db.js');
    
    // auto-create mock
    jest.mock('./path/to/db.js')
    
    
    describe('POST /user/register', () => {
    
      describe('when email Exists'), () => {
        // defining the "res" object here
        // will allow you to execute the request one
        // and separate the expectations in different
        // test cases, which will provide better visibility
        // on what exactly have failed (in the future)
        let res;
        beforeAll(async () => {
          db.doesEmailExists.mockResolvedValue({
            doesEmailExists: 789
          });
          res = await agent.post('/user/register').send(newUser);
        });
    
        it('should probably return something more than 200', () => {
          expect(res.statusCode).toBeGreaterThanOrEqual(200)
        });
    
        it('should return Error in response Body', () => {
          expect(res.body).toHaveProperty('Errors')
        });
      });
    
    
      describe('when email DOES NOT Exists'), () => {
        let res;
        beforeAll(async () => {
          db.doesEmailExists.mockResolvedValue({
            doesEmailExists: 0
          });
          res = await agent.post('/user/register').send(newUser);
        });
    
        it('should probably return statusCode 200', () => {
          expect(res.statusCode).toEqual(200)
        });
    
        it('should return token', () => {
          expect(res.body).toHaveProperty('token')
        });
      });
    });
    

    注意:您还需要模拟db.createUser 的返回值,因为自动模拟将生成一个jest.fn(),它返回undefined

    【讨论】:

    • 感谢您的明确指示。我明白你在说什么。由于我的代码返回值取决于电子邮件是否存在,我应该模拟该常量的返回,然后执行代码。快速提问是否有理由在两个新的描述测试中拔出“res”?这只是一种偏好还是你这样做是有原因的?
    • @zeke13210 我在beforeAll 块之前定义了它,因为我们向它传递了一个回调,如果我们在回调中定义它,它将在测试用例中不可见。其余的我在评论里解释过了
    猜你喜欢
    • 2018-12-01
    • 2021-03-05
    • 2018-11-09
    • 1970-01-01
    • 1970-01-01
    • 2020-05-29
    • 2020-05-20
    • 1970-01-01
    • 2019-04-30
    相关资源
    最近更新 更多