【问题标题】:Testing for valid objectId测试有效的 objectId
【发布时间】:2017-11-22 09:10:46
【问题描述】:

我正在使用 jest 来测试一个 mongoDB ObjectID。 在函数中,我检查 id 是否有效。然后我返回 ObjectId。

在我的测试中,我希望使用 ObjectId 的valueOf() 获得一个字符串,但测试失败了:

import { ObjectId } from 'mongodb'

const safeObjectId = (id) => {
  return ObjectId.isValid(id) ? new ObjectId(id) : null
}

it('should return ObjectId if it is valid', () => {
  const result = safeObjectId('5a1154523a6bcc1d245e143d')
  expect(typeof result).toBe('object')
  expect(result.valueOf()).toEqual('5a1154523a6bcc1d245e143d')
})

但我确实得到了错误

Expected value to equal:
  "5a1154523a6bcc1d245e143d"
Received:
  "5a1154523a6bcc1d245e143d"

Difference:
  Comparing two different types of values. Expected string but received object.

【问题讨论】:

    标签: javascript mongodb unit-testing jestjs


    【解决方案1】:

    你需要访问'str'属性:

    const safeObjectId = (id) => {
      return ObjectId.isValid(id) ? new ObjectId(id) : null
    }
    
    it('should return ObjectId if it is valid', () => {
      const result = safeObjectId('5a1154523a6bcc1d245e143d')
      expect(typeof result).toBe('object')
      expect(result.str).toEqual('5a1154523a6bcc1d245e143d')
    })
    

    来自文档...https://docs.mongodb.com/manual/reference/method/ObjectId/

    访问 ObjectId() 对象的 str 属性,如下:

    ObjectId("507f191e810c19729de860ea").str
    

    附言在单个测试中有多个断言是不好的做法,我会将对象检查和值检查移动到两个单独的测试中,就像这样......

    const safeObjectId = (id) => {
      return ObjectId.isValid(id) ? new ObjectId(id) : null
    }
    
    it('should return an object', () => {
      const result = safeObjectId('5a1154523a6bcc1d245e143d')
      expect(typeof result).toBe('object')
    })
    
    it('should return the correct ObjectId', () => {
      const result = safeObjectId('5a1154523a6bcc1d245e143d')
      expect(result.str).toEqual('5a1154523a6bcc1d245e143d')
    })
    

    【讨论】:

    • 最后一个测试是接收undefined。我还阅读了文档的那部分并尝试使用.str
    • 这是做什么的.. const result = safeObjectId('5a1154523a6bcc1d245e143d').str expect(result).toEqual('5a1154523a6bcc1d245e143d').
    • 同理:未定义。第一个测试通过了,所以根本就有对象……
    • 尝试在断言之前将结果转换为字符串 toString() - 我记得在断言 mongo 时看到过一次,其中值相同但 === 仍然会失败,因为类型不同,即对象与字符串
    • 如果我在第一次测试中执行console.log(result),我将得到5a1154523a6bcc1d245e143d 输出。我没有看到对象。但是测试通过了——正在检查对象类型。不明白。
    猜你喜欢
    • 2021-12-28
    • 2014-10-15
    • 2020-11-02
    • 2010-12-26
    • 2012-06-30
    • 1970-01-01
    • 1970-01-01
    • 2013-06-10
    • 1970-01-01
    相关资源
    最近更新 更多