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) })