Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create unit test for createInterview action #157

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
151 changes: 151 additions & 0 deletions actions/interviews.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
import { describe, expect, it, vi } from 'vitest';
import prisma from '~/utils/__mocks__/db';
import { createInterview } from './interviews';

// mock prisma client
vi.mock('~/utils/db', () => ({ prisma }));

// mock server-only module
vi.mock('server-only', () => ({}));

// Mock the '~/lib/analytics's module
vi.mock('@codaco/analytics', () => {
return {
makeEventTracker: vi.fn(() => {
return vi.fn(); // Mock implementation of `trackEvent`
}),
};
});

// Mock the cache.ts module
vi.mock('~/lib/cache', async (importOriginal) => {
const actual = await importOriginal<typeof import('~/lib/cache')>();
return {
...actual,
safeRevalidateTag: vi.fn(),
};
});

// vi.mock('~/lib/analytics', async (importOriginal) => {
// const actual = await importOriginal<typeof import('~/lib/analytics')>();
// return {
// ...actual,
// default: vi.fn(),
// };
// });

// Mock the '~/utils/auth' module
vi.mock('react', async (importOriginal) => {
const testCache = <T extends (...args: Array<unknown>) => unknown>(func: T) =>
func;
const originalModule = await importOriginal<typeof import('react')>();
return {
...originalModule,
cache: testCache,
};
});

describe('createInterview', () => {
it('should return an error if anonymous recruitment is not enabled and participantIdentifier is not provided ', async () => {
prisma.appSettings.findFirst.mockResolvedValue({
configured: false,
initializedAt: new Date(),
allowAnonymousRecruitment: false,
limitInterviews: false,
installationId: 'installation-id',
});

const result = await createInterview({
protocolId: 'protocol-id',
participantIdentifier: undefined,
});

expect(result).toEqual({
errorType: 'no-anonymous-recruitment',
error: 'Anonymous recruitment is not enabled',
createdInterviewId: null,
});
});

it('should create an interview with an anonymous participant if no identifier is provided', async () => {
prisma.appSettings.findFirst.mockResolvedValue({
configured: false,
initializedAt: new Date(),
allowAnonymousRecruitment: true,
limitInterviews: false,
installationId: 'installation-id',
});

prisma.interview.create.mockResolvedValue({
id: 'interview-id',
participant: {
id: 'participant-id',
identifier: 'p-generated-id',
label: 'Anonymous Participant',
},
});

const result = await createInterview({
protocolId: 'protocol-id',
participantIdentifier: undefined,
});

expect(result).toEqual({
error: null,
createdInterviewId: 'interview-id',
errorType: null,
});
});

// it('should connect a participant if an existing identifier is provided', async () => {
// prisma.appSettings.findFirst.mockResolvedValue({
// configured: false,
// initializedAt: new Date(),
// allowAnonymousRecruitment: true,
// limitInterviews: false,
// installationId: 'installation-id',
// });
// const participantIdentifier = 'existing-participant';
// const mockCreate = vi.spyOn(prisma.interview, 'create');

// prisma.interview.create.mockResolvedValue({
// id: 'interview-id',
// participant: {
// id: 'participant-id',
// identifier: participantIdentifier,
// label: 'Existing Participant',
// },
// });

// const result = await createInterview({
// protocolId: 'protocol-id',
// participantIdentifier,
// });

// expect(mockCreate).toHaveBeenCalledWith({
// select: {
// participant: true,
// id: true,
// },
// data: {
// network: Prisma.JsonNull,
// participant: {
// connect: {
// identifier: participantIdentifier,
// },
// },
// protocol: {
// connect: {
// id: 'protocol-id',
// },
// },
// },
// });

// expect(result).toEqual({
// error: null,
// createdInterviewId: 'interview-id',
// errorType: null,
// });
// });
});
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@
"tailwindcss": "^3.4.4",
"typescript": "^5.5.3",
"vite-tsconfig-paths": "^4.3.2",
"vitest": "^1.6.0"
"vitest": "^1.6.0",
"vitest-mock-extended": "^2.0.0"
}
}
27 changes: 27 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 10 additions & 0 deletions utils/__mocks__/db.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { type PrismaClient } from '@prisma/client';
import { beforeEach } from 'vitest';
import { mockDeep, mockReset } from 'vitest-mock-extended';

beforeEach(() => {
mockReset(prisma);
});

const prisma = mockDeep<PrismaClient>();
export default prisma;
19 changes: 18 additions & 1 deletion vitest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,23 @@ import { defineConfig } from 'vitest/config';
export default defineConfig({
plugins: [tsconfigPaths(), react()],
test: {
environment: 'jsdom',
environment: 'jsdom', // Default, but see below.
// Tests for actions/queries shouldn't use the browser environment, because
// they can potentially import RSC modules (such as 'server-only') which
// don't export browser versions (meaning you can't mock them).
//
// See:
// - https://github.com/vercel/next.js/issues/47448
// - https://github.com/vercel/next.js/issues/60038
//
// If you are here because your test is failing, but you can't add the whole
// path to the list below, you can also add
// `/** @vitest-environment node */` to the top of the test file on a
// case-by-case.
environmentMatchGlobs: [
// all tests in tests/dom will run in jsdom
['actions/**', 'node'],
// ...
],
},
});