我如何用Jest测试JS函数?

时间:2020-07-08 20:58:38

标签: javascript node.js express testing jestjs

对于JS,Express,Node,Jest来说是新手。但是作为一个项目,我们得到了一个陌生的新代码库,并且我们想为其添加一些功能,包括一些测试。该代码当前具有此功能,以便在signUp上创建新的User

// Create
export async function create(parentValue, { name, email, password }) {
  // Users exists with same email check
  const user = await models.User.findOne({ where: { email } })

  if (!user) {
    // User does not exists
    const passwordHashed = await bcrypt.hash(password, serverConfig.saltRounds)

    return await models.User.create({
      name,
      email,
      password: passwordHashed
    })
  } else {
    // User exists
    throw new Error(`The email ${ email } is already registered. Please try to login.`)
  }
}

这是我试图通过的测试,但是即使将信息传递给函数,我也遇到困难

import { create } from './resolvers.js'
import models from '../../setup/models'

describe("user resolvers", () => {
  test("creating a user", () => {
    expect(create({name: "test", email: "test@example.com", password: "123456"})).toMatchObject(models.User)
  })
})

1 个答案:

答案 0 :(得分:1)

首先,如果要从数据库获取创建的用户实例,则需要使用async / await。您可以选择使用嘲讽。另一点toMatchObject方法期望将类实例/对象作为参数。尝试如下:

test("creating a user", async (done) => {
  const attributes = {name: "test", email: "test@example.com", password: "123456"};
  const { name, email } = await create(attributes);
  expect(attributes).toMatchObject({ name, email });
  done();
});

注意:如果不再需要parentValue方法中的create自变量