Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
655 views
in Technique[技术] by (71.8m points)

javascript - How to verify that the property name of an object exists?

I am making jest tests for my project and I want to verify that the unique identifier of the blog posts is named id.

This is my mongoose db blog posts collection:

[
        {
          title: 'Breaking Ice',
          author: 'Mike Vasovsky',
          url: 'www.mikey.com',
          likes: 14,
          id: '5fe21b5931f6ae09d4cc58b6'
        }
]

My not finished part of the code:

test("verify id property name", async () => {
  const response = await api
    .get('/api/blogs')
  
  expect(...).toBeDefined("id")
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When in doubt, use a boolean.

expect(response && response.every(blog => blog && blog.id)).toBe(true);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

547k answers

4 comments

35.3k users

...