Как изменить значения const при тестировании с Jest - PullRequest
0 голосов
/ 22 марта 2020

Здравствуйте, я работаю над написанием теста для моего 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 в моем тесте, если это возможно, чтобы проверить разные ответы, если есть пользователь и если пользователь НЕ существует.

1 Ответ

1 голос
/ 22 марта 2020

Вы не должны издеваться над своим кодом, а скорее над вашими зависимостями и 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

...