Skip to content

Commit

Permalink
Update test files
Browse files Browse the repository at this point in the history
  • Loading branch information
m2rads committed Oct 17, 2024
1 parent c459065 commit 9330f08
Showing 1 changed file with 117 additions and 97 deletions.
214 changes: 117 additions & 97 deletions app/(dashboard)/dashboard/pull-request.test.tsx
Original file line number Diff line number Diff line change
@@ -1,56 +1,71 @@
import React from 'react';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { PullRequestItem } from './pull-request';
import { vi, describe, it, expect, beforeEach } from 'vitest';
import { PullRequest } from './types';
import useSWR from 'swr';
import { fetchBuildStatus } from '@/lib/github';

vi.mock('@/lib/github', async (importOriginal) => {
const mod = await importOriginal();
import React from "react";
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import { PullRequestItem } from "./pull-request";
import { vi, describe, it, expect, beforeEach } from "vitest";
import { PullRequest } from "./types";
import useSWR from "swr";
import { fetchBuildStatus } from "@/lib/github";
import { experimental_useObject as useObject } from "ai/react";
import { act } from "react-dom/test-utils";

vi.mock("@/lib/github", async () => {
const actual = await vi.importActual("@/lib/github");
return {
...mod,
...(actual as object),
getPullRequestInfo: vi.fn(),
commitChangesToPullRequest: vi.fn(),
getFailingTests: vi.fn(),
fetchBuildStatus: vi.fn(),
getLatestRunId: vi.fn(),
};
});

vi.mock('@/hooks/use-toast', () => ({
vi.mock("@/hooks/use-toast", () => ({
useToast: vi.fn(() => ({
toast: vi.fn(),
})),
}));

vi.mock('next/link', () => ({
default: ({ children, href }: { children: React.ReactNode; href: string }) => (
<a href={href}>{children}</a>
),
vi.mock("next/link", () => ({
default: ({
children,
href,
}: {
children: React.ReactNode;
href: string;
}) => <a href={href}>{children}</a>,
}));

vi.mock('react-diff-viewer', () => ({
vi.mock("react-diff-viewer", () => ({
default: () => <div data-testid="react-diff-viewer">Mocked Diff Viewer</div>,
}));

vi.mock('swr', () => ({
vi.mock("swr", () => ({
default: vi.fn(),
}));

describe('PullRequestItem', () => {
vi.mock("./log-view", () => ({
LogView: () => <div data-testid="log-view">Mocked Log View</div>,
}));

vi.mock("ai/react", () => ({
experimental_useObject: vi.fn(),
}));

describe("PullRequestItem", () => {
const mockPullRequest: PullRequest = {
id: 1,
title: 'Test PR',
title: "Test PR",
number: 123,
buildStatus: 'success',
buildStatus: "success",
isDraft: false,
branchName: 'feature-branch',
branchName: "feature-branch",
repository: {
id: 1,
name: 'test-repo',
full_name: 'owner/test-repo',
name: "test-repo",
full_name: "owner/test-repo",
owner: {
login: 'owner',
login: "owner",
},
},
};
Expand All @@ -65,17 +80,22 @@ describe('PullRequestItem', () => {
isValidating: false,
isLoading: false,
});
vi.mocked(useObject).mockReturnValue({
object: null,
submit: vi.fn(),
isLoading: false,
});
});

it('renders the pull request information correctly', () => {
it("renders the pull request information correctly", () => {
render(<PullRequestItem pullRequest={mockPullRequest} />);
expect(screen.getByText('Test PR')).toBeInTheDocument();
expect(screen.getByText('#123')).toBeInTheDocument();
expect(screen.getByText('Build: success')).toBeInTheDocument();
expect(screen.getByText("Test PR")).toBeInTheDocument();
expect(screen.getByText("#123")).toBeInTheDocument();
expect(screen.getByText("Build: success")).toBeInTheDocument();
});

it('displays running build status', () => {
const runningPR = { ...mockPullRequest, buildStatus: 'running' };
it("displays running build status", () => {
const runningPR = { ...mockPullRequest, buildStatus: "running" };
vi.mocked(useSWR).mockReturnValue({
data: runningPR,
mutate: vi.fn(),
Expand All @@ -84,12 +104,12 @@ describe('PullRequestItem', () => {
isLoading: false,
});
render(<PullRequestItem pullRequest={runningPR} />);
expect(screen.getByText('Build: Running')).toBeInTheDocument();
expect(screen.getByText('Running...')).toBeInTheDocument();
expect(screen.getByText("Build: Running")).toBeInTheDocument();
expect(screen.getByText("Running...")).toBeInTheDocument();
});

it('disables buttons when build is running', () => {
const runningPR = { ...mockPullRequest, buildStatus: 'running' };
it("disables buttons when build is running", () => {
const runningPR = { ...mockPullRequest, buildStatus: "running" };
vi.mocked(useSWR).mockReturnValue({
data: runningPR,
mutate: vi.fn(),
Expand All @@ -98,17 +118,18 @@ describe('PullRequestItem', () => {
isLoading: false,
});
render(<PullRequestItem pullRequest={runningPR} />);
expect(screen.getByText('Running...')).toBeDisabled();
expect(screen.getByText("Running...")).toBeDisabled();
});

it('updates build status periodically', async () => {
it("updates build status periodically", async () => {
const mutate = vi.fn();
const fetchBuildStatusMock = vi.fn().mockResolvedValue(mockPullRequest);
vi.mocked(fetchBuildStatus).mockImplementation(fetchBuildStatusMock);

vi.mocked(useSWR).mockImplementation((key, fetcher, options) => {
// Call the fetcher function to simulate SWR behavior
fetcher();
if (typeof fetcher === "function") {
fetcher();
}
return {
data: mockPullRequest,
mutate,
Expand All @@ -119,7 +140,7 @@ describe('PullRequestItem', () => {
});

render(<PullRequestItem pullRequest={mockPullRequest} />);

await waitFor(() => {
expect(useSWR).toHaveBeenCalledWith(
`pullRequest-${mockPullRequest.id}`,
Expand All @@ -132,26 +153,34 @@ describe('PullRequestItem', () => {
);
});

// Verify that fetchBuildStatus is called with the correct parameters
expect(fetchBuildStatusMock).toHaveBeenCalledWith(
mockPullRequest.repository.owner.login,
mockPullRequest.repository.name,
mockPullRequest.number
);
});

it('triggers revalidation after committing changes', async () => {
const { getPullRequestInfo, commitChangesToPullRequest } = await import('@/lib/github');
it("triggers revalidation after committing changes", async () => {
const { getPullRequestInfo, commitChangesToPullRequest } = await import(
"@/lib/github"
);
vi.mocked(getPullRequestInfo).mockResolvedValue({
diff: 'mock diff',
testFiles: [{ name: 'existing_test.ts', content: 'existing content' }],
diff: "mock diff",
testFiles: [{ name: "existing_test.ts", content: "existing content" }],
});
vi.mocked(commitChangesToPullRequest).mockResolvedValue('https://github.com/commit/123');
vi.mocked(commitChangesToPullRequest).mockResolvedValue(
"https://github.com/commit/123"
);

vi.mocked(global.fetch).mockResolvedValue({
ok: true,
json: () => Promise.resolve([{ name: 'generated_test.ts', content: 'generated content' }]),
} as Response);
const mockSubmit = vi.fn();
vi.mocked(useObject).mockReturnValue({
object: null,
submit: mockSubmit,
isLoading: false,
setInput: vi.fn(),
error: null,
stop: vi.fn(),
});

const mutate = vi.fn();
vi.mocked(useSWR).mockReturnValue({
Expand All @@ -163,14 +192,28 @@ describe('PullRequestItem', () => {
});

render(<PullRequestItem pullRequest={mockPullRequest} />);
const writeTestsButton = screen.getByText('Write new tests');

const writeTestsButton = screen.getByText("Write new tests");
fireEvent.click(writeTestsButton);

await waitFor(() => {
expect(screen.getByText('generated_test.ts')).toBeInTheDocument();
expect(screen.getByText("Analyzing PR diff...")).toBeInTheDocument();
});

await act(async () => {
const { onFinish } = vi.mocked(useObject).mock.calls[0][0];

Check failure on line 204 in app/(dashboard)/dashboard/pull-request.test.tsx

View workflow job for this annotation

GitHub Actions / test

app/(dashboard)/dashboard/pull-request.test.tsx > PullRequestItem > triggers revalidation after committing changes

TypeError: Cannot read properties of undefined (reading '0') ❯ app/(dashboard)/dashboard/pull-request.test.tsx:204:61 ❯ Object.process.env.NODE_ENV.exports.act node_modules/.pnpm/[email protected]/node_modules/react/cjs/react.development.js:1085:22 ❯ Proxy.process.env.NODE_ENV.exports.act node_modules/.pnpm/[email protected][email protected]/node_modules/react-dom/cjs/react-dom-test-utils.development.js:22:20 ❯ app/(dashboard)/dashboard/pull-request.test.tsx:203:11
await onFinish({
object: {
tests: [{ name: "generated_test.ts", content: "generated content" }],
},
});
});

const commitButton = screen.getByText('Commit changes');
await waitFor(() => {
expect(screen.getByText("generated_test.ts")).toBeInTheDocument();
});

const commitButton = screen.getByText("Commit changes");
fireEvent.click(commitButton);

await waitFor(() => {
Expand All @@ -179,59 +222,36 @@ describe('PullRequestItem', () => {
});
});

it('handles commit message input', async () => {
it("shows and hides logs when toggle is clicked", async () => {
vi.mocked(useSWR).mockReturnValue({
data: { ...mockPullRequest, buildStatus: "success" },
mutate: vi.fn(),
error: undefined,
isValidating: false,
isLoading: false,
});

const { getLatestRunId } = await import("@/lib/github");
vi.mocked(getLatestRunId).mockResolvedValue("123");

render(<PullRequestItem pullRequest={mockPullRequest} />);
const writeTestsButton = screen.getByText('Write new tests');
fireEvent.click(writeTestsButton);

await waitFor(() => {

Check failure on line 239 in app/(dashboard)/dashboard/pull-request.test.tsx

View workflow job for this annotation

GitHub Actions / test

app/(dashboard)/dashboard/pull-request.test.tsx > PullRequestItem > shows and hides logs when toggle is clicked

TestingLibraryElementError: Unable to find an element with the text: Show Logs. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible. Ignored nodes: comments, script, style <body> <div> <div class="bg-white p-4 rounded-lg shadow-md" > <div class="flex items-center justify-between mb-2" > <span class="flex items-center" > <svg class="lucide lucide-git-pull-request mr-2 h-4 w-4" fill="none" height="24" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg" > <circle cx="18" cy="18" r="3" /> <circle cx="6" cy="6" r="3" /> <path d="M13 6h3a2 2 0 0 1 2 2v7" /> <line x1="6" x2="6" y1="9" y2="21" /> </svg> <span class="font-medium" > Test PR </span> </span> <a href="https://github.com/owner/test-repo/pull/123" > # 123 </a> </div> <div class="flex items-center justify-between" > <span class="flex items-center" > <svg class="lucide lucide-circle-check-big mr-2 h-4 w-4 text-green-500" fill="none" height="24" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg" > <path d="M21.801 10A10 10 0 1 1 17 3.335" /> <path d="m9 11 3 3L22 4" /> </svg> <a href="https://github.com/owner/test-repo/pull/123/checks" > Build: success </a> </span> <button class="inline-flex items-center justify-center whitespace-nowrap font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 shadow h-8 rounded-md px-3 text-xs bg-green-500 hover:bg-green-600 text-white" > <svg class="lucide lucide-circle-plus mr-2 h-4 w-4" fill="none" height="24" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg" > <circle cx="12" cy="12" r="10" /> <path d="M8 12h8" /> <path d="M12 8v8" /> </svg> Write new tests </button> </div> </div> </div> </body> Ignored nodes: comments, script, style <html> <head /> <body> <div> <div class="bg-white p-4 rounded-lg shadow-md" > <div class="flex items-center justify-between mb-2" > <span class="flex items-center" > <svg class="lucide lucide-git-pull-request mr-2 h-4 w-4" fill="none" height="24" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg" >
const commitMessageInput = screen.getByPlaceholderText('Update test files');
expect(commitMessageInput).toBeInTheDocument();
fireEvent.change(commitMessageInput, { target: { value: 'Custom commit message' } });
expect(commitMessageInput).toHaveValue('Custom commit message');
expect(screen.getByText("Show Logs")).toBeInTheDocument();
});
});

it('disables commit button when commit message is empty', async () => {
render(<PullRequestItem pullRequest={mockPullRequest} />);
const writeTestsButton = screen.getByText('Write new tests');
fireEvent.click(writeTestsButton);
fireEvent.click(screen.getByText("Show Logs"));

await waitFor(() => {
const commitMessageInput = screen.getByPlaceholderText('Update test files');
const commitButton = screen.getByText('Commit changes');

fireEvent.change(commitMessageInput, { target: { value: '' } });
expect(commitButton).toBeDisabled();

fireEvent.change(commitMessageInput, { target: { value: 'Valid message' } });
expect(commitButton).not.toBeDisabled();
expect(screen.getByTestId("log-view")).toBeInTheDocument();
expect(screen.getByText("Hide Logs")).toBeInTheDocument();
});
});

it('handles pending build status', () => {
const pendingPR = { ...mockPullRequest, buildStatus: 'pending' };
vi.mocked(useSWR).mockReturnValue({
data: pendingPR,
mutate: vi.fn(),
error: undefined,
isValidating: false,
isLoading: false,
});
render(<PullRequestItem pullRequest={pendingPR} />);
expect(screen.getByText('Build: Pending')).toBeInTheDocument();
});
fireEvent.click(screen.getByText("Hide Logs"));

it('handles unknown build status', () => {
const unknownPR = { ...mockPullRequest, buildStatus: 'unknown' };
vi.mocked(useSWR).mockReturnValue({
data: unknownPR,
mutate: vi.fn(),
error: undefined,
isValidating: false,
isLoading: false,
await waitFor(() => {
expect(screen.queryByTestId("log-view")).not.toBeInTheDocument();
expect(screen.getByText("Show Logs")).toBeInTheDocument();
});
render(<PullRequestItem pullRequest={unknownPR} />);
expect(screen.getByText('Build: unknown')).toBeInTheDocument();
});
});

0 comments on commit 9330f08

Please sign in to comment.