Skip to content

Commit

Permalink
test: setup tests using msw mocks
Browse files Browse the repository at this point in the history
  • Loading branch information
PupoSDC committed Aug 11, 2023
1 parent 5abfaf8 commit c9b0a9a
Show file tree
Hide file tree
Showing 25 changed files with 356 additions and 76 deletions.
3 changes: 3 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"singleQuote": true
}
6 changes: 3 additions & 3 deletions apps/docs/.storybook/preview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ import { CssVarsProvider, extendTheme, useColorScheme } from "@mui/joy/styles";
import { DocsContainer, DocsContainerProps } from "@storybook/addon-docs";
import { Preview } from "@storybook/react";
import { themes } from "@storybook/theming";
import { initialize, mswLoader } from "msw-storybook-addon";
import { initialize, mswDecorator, mswLoader } from "msw-storybook-addon";
import { useDarkMode } from "storybook-dark-mode";
import { trpc } from "@chair-flight/trpc/client";
import { theme } from "../../../libs/react/components/src/theme";
import { theme } from "@chair-flight/react/components";
import type { TypographyProps } from "@mui/joy";
import "@fontsource/public-sans";

Expand Down Expand Up @@ -90,6 +90,7 @@ const preview: Preview = {
<Story />
</Suspense>
),
mswDecorator,
(Story) => {
const Component = trpc.withTRPC(Story);
return <Component />;
Expand All @@ -102,7 +103,6 @@ const preview: Preview = {
</CssVarsProvider>
),
],
loaders: [mswLoader],
};

export default preview;
13 changes: 10 additions & 3 deletions apps/next-app/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,16 @@
"jsx": "preserve",
"isolatedModules": true,
"incremental": true,
"types": ["node", "react"],
"lib": ["esnext", "dom"],
"allowJs": true
"types": [
"node",
"react"
],
"lib": [
"esnext",
"dom"
],
"allowJs": true,
"esModuleInterop": true
},
"include": [],
"references": [
Expand Down
4 changes: 2 additions & 2 deletions libs/providers/github/src/functions/create-new-question-pr.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { default as babelPlugin } from "prettier/plugins/babel";
import { default as estreePlugin } from "prettier/plugins/estree";
import * as babelPlugin from "prettier/plugins/babel";
import * as estreePlugin from "prettier/plugins/estree";
import { format } from "prettier/standalone";
import { getRandomId } from "@chair-flight/core/app";
import { getOctokit } from "../config/oktokit";
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { default as fs } from "fs";
import { default as path } from "path";
import { cwd } from "process";
import * as fs from "fs";
import * as path from "path";
import * as process from "process";
import * as XLSX from "xlsx";
import type {
CourseName,
Expand All @@ -26,7 +26,7 @@ const courseNames: Record<string, CourseName> = {
};

export const getAllQuestionsFromLocalFs = async (
dirPath: string = path.join(cwd(), contentPath, "questions"),
dirPath: string = path.join(process.cwd(), contentPath, "questions"),
): Promise<QuestionTemplate[]> => {
const files = fs.readdirSync(dirPath);
const questions: QuestionTemplate[] = [];
Expand All @@ -41,7 +41,7 @@ export const getAllQuestionsFromLocalFs = async (
) as QuestionTemplateJson[];
const jsonDataWithSrcLocation = jsonData.map((q) => ({
...q,
srcLocation: filePath.replace(cwd(), ""),
srcLocation: filePath.replace(process.cwd(), ""),
}));
questions.push(...jsonDataWithSrcLocation);
}
Expand All @@ -52,7 +52,7 @@ export const getAllQuestionsFromLocalFs = async (
};

export const getAllFlashCardsFromLocalFs = async (
dirPath: string = path.join(cwd(), contentPath, "flash-cards"),
dirPath: string = path.join(process.cwd(), contentPath, "flash-cards"),
): Promise<Record<string, FlashCardContent[]>> => {
const files = fs.readdirSync(dirPath);
const flashCards: Record<string, FlashCardContent[]> = {};
Expand All @@ -69,7 +69,7 @@ export const getAllFlashCardsFromLocalFs = async (
};

export const getAllLearningObjectivesFromLocalFs = async () => {
const fileName = path.join(cwd(), contentPath, "external/tk-syllabus.xlsx");
const fileName = path.join(process.cwd(), contentPath, "external/tk-syllabus.xlsx");
const questions = await getAllQuestionsFromLocalFs();
const workbook = XLSX.readFile(fileName);
const sheetNames = workbook.SheetNames;
Expand Down Expand Up @@ -141,7 +141,7 @@ export const getAllLearningObjectivesFromLocalFs = async () => {

export const getAllSubjectsFromLocalFs = async () => {
const allLearningObjectives = await getAllLearningObjectivesFromLocalFs();
const filePath = path.join(cwd(), contentPath, "subjects/subjects.json");
const filePath = path.join(process.cwd(), contentPath, "subjects/subjects.json");
const fileBuffer = fs.readFileSync(filePath, "utf-8");
const subjects = JSON.parse(fileBuffer) as SubjectJson[];

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { default as fs } from "fs";
import { default as path } from "path";
import * as fs from "fs";
import * as path from "path";
import { cwd } from "process";
import type {
QuestionTemplate,
Expand Down
2 changes: 1 addition & 1 deletion libs/react/components/project.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
},
"test": {
"executor": "@nrwl/vite:test",
"outputs": ["coverage/libs/react/components"],
"outputs": [],
"options": {
"passWithNoTests": false,
"reportsDirectory": "../../../coverage/libs/react/components"
Expand Down
2 changes: 1 addition & 1 deletion libs/react/components/src/__tests__/setup-tests.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { default as matchers } from "@testing-library/jest-dom/matchers";
import * as matchers from "@testing-library/jest-dom/matchers";
import { cleanup } from "@testing-library/react";
import { afterEach, expect } from "vitest";

Expand Down
4 changes: 2 additions & 2 deletions libs/react/containers/project.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@
},
"test": {
"executor": "@nrwl/vite:test",
"outputs": ["coverage/libs/react/containers"],
"outputs": [],
"options": {
"passWithNoTests": true,
"passWithNoTests": false,
"reportsDirectory": "../../../coverage/libs/react/containers"
}
}
Expand Down
84 changes: 84 additions & 0 deletions libs/react/containers/src/__tests__/decorators.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import { trpc } from '@chair-flight/trpc/client';
import { CssBaseline, CssVarsProvider } from '@mui/joy';
import { RouterContext } from 'next/dist/shared/lib/router-context';
import { FunctionComponent, Suspense } from 'react';
import { mswDecorator } from 'msw-storybook-addon';
import { theme } from "../theme";
import { vi } from 'vitest';

export const action = vi.fn();

export const decorators = [
(Story: FunctionComponent) => (
<Suspense fallback="Loading...">
<Story />
</Suspense>
),
(Story: FunctionComponent) => (
<CssVarsProvider theme={theme}>
<CssBaseline />
<Story />
</CssVarsProvider>
),
(Story: FunctionComponent, other: any) => (
<RouterContext.Provider
value={{
push(...args: unknown[]) {
action('nextRouter.push')(...args);
return Promise.resolve(true);
},
replace(...args: unknown[]) {
action('nextRouter.replace')(...args);
return Promise.resolve(true);
},
reload(...args: unknown[]) {
action('nextRouter.reload')(...args);
},
back(...args: unknown[]) {
action('nextRouter.back')(...args);
},
forward() {
action('nextRouter.forward')();
},
prefetch(...args: unknown[]) {
action('nextRouter.prefetch')(...args);
return Promise.resolve();
},
beforePopState(...args: unknown[]) {
action('nextRouter.beforePopState')(...args);
},
events: {
on(...args: unknown[]) {
action('nextRouter.events.on')(...args);
},
off(...args: unknown[]) {
action('nextRouter.events.off')(...args);
},
emit(...args: unknown[]) {
action('nextRouter.events.emit')(...args);
},
},
locale: other?.globals?.locale,
route: '/',
asPath: '/',
basePath: '/',
isFallback: false,
isLocaleDomain: false,
isReady: true,
isPreview: false,
pathname: '/',
query: {},
...other?.parameters.nextjs?.router,

}}
>
<Story />
</RouterContext.Provider>
),
(Story: FunctionComponent) => {
const Component = trpc.withTRPC(Story);
return <Component />;
},
mswDecorator,
];

33 changes: 33 additions & 0 deletions libs/react/containers/src/__tests__/setup-tests.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import * as matchers from "@testing-library/jest-dom/matchers";
import { cleanup } from "@testing-library/react";
import { afterEach, expect, vi } from "vitest";
import { initialize } from "msw-storybook-addon";

expect.extend(matchers);

initialize({
onUnhandledRequest: 'error',
});


beforeAll(() => {
Object.defineProperty(window, 'matchMedia', {
writable: true,
value: vi.fn().mockImplementation(query => ({
matches: false,
media: query,
onchange: null,
addListener: vi.fn(), // deprecated
removeListener: vi.fn(), // deprecated
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
dispatchEvent: vi.fn(),
})),
})
});

afterEach(() => {
cleanup();
});


Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,7 @@ export const EditVariants: FunctionComponent = () => {
openVariant={openVariant}
deleteVariant={deleteVariant}
mergeVariants={mergeVariants}
data-testid={`variant-card`}
/>
))}
</ListContainer>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export type InputAutocompleteLearningObjectivesProps = {
export const InputAutocompleteLearningObjectives = forwardRef<
HTMLDivElement,
InputAutocompleteLearningObjectivesProps
>(({ value, onChange, onBlur }) => {
>(({ value, onChange, onBlur }, ref) => {
const [search, setSearch] = useState("");

const { data, isLoading } = trpc.search.searchLearningObjectives.useQuery({
Expand All @@ -28,6 +28,9 @@ export const InputAutocompleteLearningObjectives = forwardRef<
return acc;
}, {});

// todo foward this when joy fixes autocomplete
ref = ref ?? null;

return (
<Autocomplete
multiple
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { mockQuestion, trpcMsw } from "@chair-flight/trpc/mock";
import { trpc } from "@chair-flight/trpc/client";
import { QuestionEditor } from "./question-editor";
import type { Meta, StoryObj } from "@storybook/react";
import { rest } from "msw";
import { useEffect, useState } from "react";

type Story = StoryObj<typeof QuestionEditor>;

Expand Down Expand Up @@ -45,6 +48,18 @@ export const VariantOneTwoEditor: Story = {
},
};

export const VariantSTupid: Story = {
render: () => {
const [a, setA] = useState("potato");

trpc.questions.getQuestionFromGithub.useQuery({
questionId: "124",
});

return <h1>{a}</h1>
}
}

const meta: Meta<typeof QuestionEditor> = {
title: "Containers/Questions/QuestionEditor",
component: QuestionEditor,
Expand All @@ -58,6 +73,7 @@ const meta: Meta<typeof QuestionEditor> = {
},
msw: [
trpcMsw.questions.getQuestionFromGithub.query((req, res, ctx) => {
console.log("potatooooo");
return res(
ctx.status(200),
ctx.data({ questionTemplate: mockQuestion }),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { composeStories } from '@storybook/react';
import * as stories from './question-editor.stories';
import { render, screen, waitForElementToBeRemoved } from '@testing-library/react';
import { default as userEvent } from '@testing-library/user-event';
import { decorators } from '../../__tests__/decorators'
import { setupServer } from 'msw/node';
import { rest } from 'msw';
import { useEffect, useState } from 'react';
import { getWorker } from 'msw-storybook-addon';

const { BasePage, VariantSTupid } = composeStories(stories, { decorators });

describe('QuestionEditor', () => {


it('is possible to create a new variant', async () => {
render(<BasePage />);

const loading = screen.getByText("Loading...");
await waitForElementToBeRemoved(loading);



//const initialCards = await screen.findAllByTestId('variant-card');
//const addButton = screen.getByRole('button', { name: /new variant/i });
//await userEvent.click(addButton,);
//const newCards = await screen.findAllByTestId('variant-card');
//expect(initialCards.length + 1).toBe(newCards.length);
});

it.only("works with really simple case", async () => {

render(<VariantSTupid />);

//getWorker().listHandlers();

await screen.findByText("potato");
await screen.findByText("starting");
// await waitForElementToBeRemoved(loading);

})
});

Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { EditVariantModal } from "./components/edit-variant-modal";
import { EditVariants } from "./components/edit-variants";
import { ReviewPrModal } from "./review-pr-modal";
import type { EditQuestionFormValues } from "./types/edit-question-form-values";
import { useEffect } from "react";

const resolver = zodResolver(questionEditSchema);
const useQuestion = trpc.questions.getQuestionFromGithub.useSuspenseQuery;
Expand Down
Loading

0 comments on commit c9b0a9a

Please sign in to comment.