Skip to content

Unit Testing shows flawed test example #4455

Description

@DanielMenke

this test:

test('should fail if user does not accept terms', async () => {
  const user = {
    id: 1,
    name: 'Rich Haines',
    email: 'hello@prisma.io',
    acceptTermsAndConditions: false,
  }

  prismaMock.user.create.mockRejectedValue(new Error('User must accept terms!'))

  await expect(createUser(user)).resolves.toEqual(
    new Error('User must accept terms!')
  )
})

tests this function:

export async function createUser(user: CreateUser, ctx: Context) {
  if (user.acceptTermsAndConditions) {
    return await ctx.prisma.user.create({
      data: user,
    }) // ALWAY THROWS, DUE TO THE MOCK
  } else {
    return new Error('User must accept terms!')
  }
}

This line
prismaMock.user.create.mockRejectedValue(new Error('User must accept terms!'))

lets the test succeed no matter which path the execution goes. If the code gets changed in some way that ctx.prisma.user.create actually gets executed, the test would suggest that the guard is still intact although it isn't.

Metadata

Metadata

Assignees

Labels

type/docsDocumentation creation, updates or corrections

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions