[Unit testing] Simplify Assertions on Error Messages with toMatchInlineSnapshot

Let’s add a test for an edge case that responds with an error message. In this lesson we’ll talk about the value of using the toMatchInlineSnapshot assertion for error messages.

 

Code:

async function createListItem(req, res) {
  const {
    user: {id: ownerId},
  } = req
  const {bookId} = req.body
  if (!bookId) {
    res.status(400).json({message: `nwo bookId provided`})
    return
  }
  const [existingListItem] = await listItemsDB.query({ownerId, bookId})
  if (existingListItem) {
    res.status(400).json({
      message: `User ${ownerId} already has a list item for the book with the ID ${bookId}`,
    })
    return
  }

  const listItem = await listItemsDB.create({ownerId, bookId})
  res.json({listItem: await expandBookData(listItem)})
}

 

Test:

test('createListItem return a 400 error with no bookId', async () => {
  const req = buildReq()
  const res = buildRes()

  await listItemsController.createListItem(req, res)

  expect(res.status).toHaveBeenCalledWith(400)
  expect(res.status).toHaveBeenCalledTimes(1)
  //expect(res.json).toHaveBeenCalledWith({message: `No bookId provided`})
  expect(res.json.mock.calls[0]).toMatchInlineSnapshot(`
    Array [
      Object {
        "message": "no bookId provided",
      },
    ]
  `)
  expect(res.json).toHaveBeenCalledTimes(1)
})

 

posted @ 2021-08-16 14:45  Zhentiw  阅读(57)  评论(0编辑  收藏  举报