【问题标题】:How would I test a JS function with Jest?如何使用 Jest 测试 JS 函数?
【发布时间】:2020-10-29 09:08:02
【问题描述】:

JS、Express、Node、Jest 的新手...但是作为一个项目,我们得到了一个新的不熟悉的代码库,我们假设要向它添加一些功能,包括一些测试。代码目前有这个功能,以便在注册时创建一个新的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)
  })
})

【问题讨论】:

    标签: javascript node.js express testing jestjs


    【解决方案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 方法中删除它

    【讨论】:

    • 我不完全知道 parentValue 在做什么,但我做了更改并且它们有意义 - 但我仍然收到错误 TypeError: Cannot read property 'name' of undefined 这仍然让我认为它没有通过属性通过正确。
    • 如果您已经删除了parentValue,并且您的方法看起来像... function create( { name, email, password }),那么您需要检查您的模型和数据库中是否有name 属性。请检查它是否在您的用户表中创建了新记录。你不需要在这里有 await 关键字:return await models.User.create
    猜你喜欢
    • 2020-06-04
    • 2020-06-22
    • 2020-11-30
    • 1970-01-01
    • 2020-10-27
    • 2019-07-22
    • 2017-09-18
    • 2019-01-04
    • 1970-01-01
    相关资源
    最近更新 更多