我正在使用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.
答案 0 :(得分:0)
您需要访问'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
P.S。在单个测试中使用多个断言是不好的做法,我会将对象检查和值检查移动到两个单独的测试中,如此...
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')
})