chore(api): migrate tests to Vitest v4 (#65950)

This commit is contained in:
Jeevankumar S
2026-02-21 08:43:50 +05:30
committed by GitHub
parent b249098466
commit eb44f8b43c
9 changed files with 125 additions and 171 deletions
@@ -1,4 +1,5 @@
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
import type { MockInstance } from 'vitest';
import {
ExamEnvironmentAnswer,
ExamEnvironmentQuestionType
@@ -29,7 +30,7 @@ import {
// generate a valid exam.
// Another option is to call `generateExam` hundreds of times in a loop test :shrug:
describe('Exam Environment mocked Math.random', () => {
let spy: ReturnType<typeof vi.spyOn>;
let spy: MockInstance;
beforeAll(() => {
spy = vi.spyOn(Math, 'random').mockReturnValue(0.123456789);
});
+7 -7
View File
@@ -50,8 +50,8 @@ describe('findOrCreateUser', () => {
afterEach(async () => {
await fastify.prisma.user.deleteMany({ where: { email } });
await fastify.prisma.dripCampaign.deleteMany({ where: { email } });
await fastify.close();
vi.clearAllMocks();
vi.restoreAllMocks();
captureException.mockReset();
});
test('should send a message to Sentry if there are multiple users with the same email', async () => {
@@ -130,9 +130,10 @@ describe('findOrCreateUser', () => {
test('should not prevent user creation if drip campaign record creation fails', async () => {
vi.spyOn(fastify.gb, 'isOn').mockImplementationOnce(() => true);
// Mock dripCampaign.create to throw an error
const createSpy = vi
.spyOn(fastify.prisma.dripCampaign, 'create')
const originalCreate = fastify.prisma.dripCampaign.create;
fastify.prisma.dripCampaign.create = vi
.fn()
.mockRejectedValueOnce(new Error('Database error'));
const user = await findOrCreateUser(fastify, email);
@@ -140,7 +141,6 @@ describe('findOrCreateUser', () => {
expect(user).toBeDefined();
expect(user.id).toBeTruthy();
// Verify error was captured by Sentry
expect(captureException).toHaveBeenCalledTimes(1);
expect(captureException).toHaveBeenCalledWith(
expect.objectContaining({
@@ -148,7 +148,7 @@ describe('findOrCreateUser', () => {
})
);
createSpy.mockRestore();
fastify.prisma.dripCampaign.create = originalCreate;
});
test('should not create drip campaign for existing users', async () => {
+4 -5
View File
@@ -424,11 +424,10 @@ describe('certificate routes', () => {
}
});
vi.spyOn(fastifyTestInstance.prisma.user, 'update').mockImplementation(
() => {
throw new Error('test');
}
);
vi.spyOn(fastifyTestInstance.prisma, 'user', 'get').mockReturnValue({
...fastifyTestInstance.prisma.user,
update: vi.fn().mockRejectedValueOnce(new Error('test'))
});
const response = await superRequest('/certificate/verify', {
method: 'PUT',
+10 -4
View File
@@ -378,11 +378,17 @@ describe('challengeRoutes', () => {
// function with undefined when restoring a prisma function (for some
// reason)
test('Should return an error response if something goes wrong', async () => {
const originalUserToken = fastifyTestInstance.prisma.userToken;
vi.spyOn(
fastifyTestInstance.prisma.userToken,
'findUnique'
).mockImplementationOnce(() => {
throw new Error('Database error');
fastifyTestInstance.prisma,
'userToken',
'get'
).mockReturnValue({
...originalUserToken,
findUnique: vi.fn().mockImplementationOnce(() => {
throw new Error('Database error');
})
});
const tokenResponse = await superPost('/user/user-token');
const token = (tokenResponse.body as { userToken: string }).userToken;
+25 -24
View File
@@ -124,30 +124,31 @@ const generateMockSubCreate = (status: string) => () =>
const defaultError = () =>
Promise.reject(new Error('Stripe encountered an error'));
vi.mock('stripe', () => {
return {
default: vi.fn().mockImplementation(() => {
return {
customers: {
create: mockCustomerCreate,
update: mockCustomerUpdate
},
paymentMethods: {
attach: mockAttachPaymentMethod
},
subscriptions: {
create: mockSubCreate,
retrieve: mockSubRetrieve
},
checkout: {
sessions: {
create: mockCheckoutSessionCreate
}
}
};
})
};
});
vi.mock('stripe', () => ({
default: class {
constructor() {}
customers = {
create: mockCustomerCreate,
update: mockCustomerUpdate
};
paymentMethods = {
attach: mockAttachPaymentMethod
};
subscriptions = {
create: mockSubCreate,
retrieve: mockSubRetrieve
};
checkout = {
sessions: {
create: mockCheckoutSessionCreate
}
};
}
}));
describe('Donate', () => {
let setCookies: string[];
+8 -7
View File
@@ -602,16 +602,17 @@ Please wait 5 minutes to resend an authentication link.`
// function with undefined when restoring a prisma function (for some
// reason)
test('PUT sends an email to the new email address', async () => {
const originalAuthToken = fastifyTestInstance.prisma.authToken;
vi.spyOn(
fastifyTestInstance.prisma.authToken,
'create'
).mockImplementationOnce(() =>
// @ts-expect-error This is a mock implementation, all we're
// interested in is the id.
Promise.resolve({
fastifyTestInstance.prisma,
'authToken',
'get'
).mockReturnValue({
...originalAuthToken,
create: vi.fn().mockResolvedValue({
id: '123'
})
);
});
await superPut('/update-my-email').send({
email: unusedEmailOne
});
+21 -25
View File
@@ -66,31 +66,27 @@ const generateMockSubCreate = (status: string) => () =>
}
}
});
vi.mock('stripe', () => {
return {
default: vi.fn().mockImplementation(() => {
return {
customers: {
create: mockCustomerCreate,
update: mockCustomerUpdate
},
paymentMethods: {
attach: mockAttachPaymentMethod
},
subscriptions: {
create: mockSubCreate,
retrieve: mockSubRetrieve
},
checkout: {
sessions: {
create: mockCheckoutSessionCreate
}
}
};
})
};
});
vi.mock('stripe', () => ({
default: class {
constructor() {}
customers = {
create: mockCustomerCreate,
update: mockCustomerUpdate
};
paymentMethods = {
attach: mockAttachPaymentMethod
};
subscriptions = {
create: mockSubCreate,
retrieve: mockSubRetrieve
};
checkout = {
sessions: {
create: mockCheckoutSessionCreate
}
};
}
}));
describe('Donate', () => {
let setCookies: string[];
setupServer();