Skip to content

Commit

Permalink
more coverage
Browse files Browse the repository at this point in the history
  • Loading branch information
k2xl committed Dec 27, 2023
1 parent f0a1bcb commit 305ffa0
Show file tree
Hide file tree
Showing 10 changed files with 28 additions and 183 deletions.
2 changes: 1 addition & 1 deletion helpers/genImage.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// pages/api/render-grid.js
/* istanbul ignore file */

import { getGameFromId } from '@root/helpers/getGameIdFromReq';
import Level from '@root/models/db/level';
Expand Down
2 changes: 1 addition & 1 deletion helpers/generateLevelCanvas.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
/* istanbul ignore file */
import TileType, { TileTypeDefaultVisited } from '@root/constants/tileType';
import TileTypeHelper from '@root/helpers/tileTypeHelper';
import { Bitmap } from 'pureimage';

/* istanbul ignore next */
export default function generateLevelCanvas(canvas: Bitmap | HTMLCanvasElement, levelData: string) {
const levelRows = levelData.split('\n');
const height = levelRows.length;
Expand Down
2 changes: 1 addition & 1 deletion helpers/getPngDataClient.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* istanbul ignore file */
import Dimensions from '../constants/dimensions';
import generateLevelCanvas from './generateLevelCanvas';

/* istanbul ignore next */
export default function getPngDataClient(levelData: string) {
if (typeof document === 'undefined') {
return;
Expand Down
24 changes: 0 additions & 24 deletions helpers/getPngDataServer.ts

This file was deleted.

1 change: 1 addition & 0 deletions helpers/imageTools.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* istanbul ignore file */
// https://gist.github.com/dcollien/312bce1270a5f511bf4a?permalink_comment_id=2265490#gistcomment-2265490
/* eslint-disable @typescript-eslint/no-explicit-any */
const hasBlobConstructor = typeof (Blob) !== 'undefined' && (function () {
Expand Down
3 changes: 3 additions & 0 deletions pages/[subdomain]/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export async function getServerSideProps(context: GetServerSidePropsContext) {
};
}

/* istanbul ignore next */
export interface HomepageDataProps {
latestLevels?: EnrichedLevel[];
latestReviews?: Review[];
Expand All @@ -43,10 +44,12 @@ export interface HomepageDataProps {
topLevelsThisMonth?: EnrichedLevel[];
}

/* istanbul ignore next */
interface HomePageProps {
user: User | null;
}

/* istanbul ignore next */
export function isVisibleInDom(id: string) {
const element = document.getElementById(id);

Expand Down
5 changes: 3 additions & 2 deletions pages/api/level/image/[id].ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,9 @@ export default apiWrapper({ GET: {
pngData = levelImage.image;
res.setHeader('Content-Length', pngData.length);

Check warning on line 50 in pages/api/level/image/[id].ts

View check run for this annotation

Codecov / codecov/patch

pages/api/level/image/[id].ts#L50

Added line #L50 was not covered by tests
} else {
logger.warn(`Image not found for level ${levelId}`);
throw new Error('Image not found');
return res.status(404).json({
error: 'Image not found for level',
});
}
});
session.endSession();
Expand Down
4 changes: 2 additions & 2 deletions pages/index.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* istanbul ignore file */
import Footer from '@root/components/page/footer';
import Page from '@root/components/page/page';
import { GameId } from '@root/constants/GameId';
Expand All @@ -8,7 +9,6 @@ import Image from 'next/image';
import React, { useContext } from 'react';
import { BannerLayer, Parallax, ParallaxBanner, ParallaxProvider } from 'react-scroll-parallax';

/* istanbul ignore next */
export default function ThinkyHomePage() {
function GameCard({ game }: { game: Game }) {
const getUrl = useUrl();
Expand Down Expand Up @@ -83,7 +83,7 @@ export default function ThinkyHomePage() {
expanded: false,
children: (
<div className='justify-center flex flex-col items-center'>
<h1 className='text-6xl md:text-8xl text-white font-thin bg-black p-3 rounded-lg'>
<h1 className='text-6xl md:text-8xl text-white font-thin p-3 rounded-lg'>
Thinky.gg
</h1>
<div className='flex justify-center'>
Expand Down
8 changes: 7 additions & 1 deletion tests/helpers/helpers.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import StatFilter from '@root/constants/statFilter';
import { generatePassword } from '@root/helpers/generatePassword';
import TestId from '../../constants/testId';
import statFilterOptions from '../../helpers/filterSelectOptions';
import getDifficultyEstimate from '../../helpers/getDifficultyEstimate';
Expand Down Expand Up @@ -151,6 +152,11 @@ describe('helpers/*.ts', () => {

expect(getDifficultyEstimate(level, 10)).toBe(0);
});
test('generatePassword', async () => {
const password = generatePassword();

expect(password.length).toBeGreaterThan(0);
});
});

export {};
export { };
160 changes: 9 additions & 151 deletions tests/pages/api/level/level.image.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { DEFAULT_GAME_ID } from '@root/constants/GameId';
import TestId from '@root/constants/testId';
import { NextApiRequestWrapper } from '@root/helpers/apiWrapper';
import { TimerUtil } from '@root/helpers/getTs';
import { getTokenCookieValue } from '@root/lib/getTokenCookie';
import { NextApiRequestWithAuth } from '@root/lib/withAuth';
import { LevelModel } from '@root/models/mongoose';
import { processQueueMessages } from '@root/pages/api/internal-jobs/worker';
import generateImageHandler from '@root/pages/api/level/image/[id]';
import publishLevelHandler from '@root/pages/api/publish/[id]';
import { enableFetchMocks } from 'jest-fetch-mock';
import { testApiHandler } from 'next-test-api-route-handler';
Expand Down Expand Up @@ -61,46 +63,10 @@ describe('pages/api/level/image/[id]', () => {

expect(response.error).toBeUndefined();
expect(res.status).toBe(200);

await processQueueMessages();
},
});
});

/*test('Now we should be able to get the level image', async () => {
//Dimensions.LevelCanvasWidth and Dimensions.LevelCanvasHeight mocked to return 1
// This speeds up the test by about 6 seconds
Object.defineProperty(Dimensions, 'LevelCanvasWidth', { value: 1 });
Object.defineProperty(Dimensions, 'LevelCanvasHeight', { value: 1 });
expect(Dimensions.LevelCanvasWidth).toBe(1);
await testApiHandler({
handler: async (_, res) => {
const req: NextApiRequestWrapper = {
gameId: DEFAULT_GAME_ID,
method: 'GET',
query: {
id: TestId.LEVEL,
},
} as unknown as NextApiRequestWrapper;
await getLevelImageHandler(req, res);
},
test: async ({ fetch }) => {
const res = await fetch();
expect(res.status).toBe(200);
const body = await res.body.read();
// expect header to be image
expect(res.headers.get('content-type')).toBe('image/png');
expect(body.length).toBe(82); // small due to mocked dimensions
},
});
}, 30000);
test('GET a second time to get the cached image', async () => {
test('Now we should NOT able to get the level image since we have not generated it yet', async () => {
await testApiHandler({
handler: async (_, res) => {
const req: NextApiRequestWrapper = {
Expand All @@ -111,125 +77,17 @@ describe('pages/api/level/image/[id]', () => {
},
} as unknown as NextApiRequestWrapper;

await getLevelImageHandler(req, res);
},
test: async ({ fetch }) => {
const res = await fetch();
expect(res.status).toBe(200);
const body = await res.body.read();
// expect header to be image
expect(res.headers.get('content-type')).toBe('image/png');
expect(body.length).toBe(82);
},
});
}, 30000);
test('Requesting an image for a level that doesn\'t exist should 404', async () => {
await testApiHandler({
handler: async (_, res) => {
const req: NextApiRequestWrapper = {
gameId: DEFAULT_GAME_ID,
method: 'GET',
query: {
id: new Types.ObjectId().toString(),
},
} as unknown as NextApiRequestWrapper;
await getLevelImageHandler(req, res);
await generateImageHandler(req, res);
},
test: async ({ fetch }) => {
const res = await fetch();

expect(res.status).toBe(404);
const response = await res.json();
// expect header to be json
expect(res.headers.get('content-type')).toBe('application/json; charset=utf-8');
expect(response.error).toBe('Level not found');
},
});
}, 30000);
test('Requesting an image for a draft level should 401', async () => {
let draftLevelId: string;
await testApiHandler({
handler: async (_, res) => {
const req: NextApiRequestWithAuth = {
method: 'POST',
cookies: {
token: getTokenCookieValue(TestId.USER),
},
body: {
authorNote: 'I\'m a nice little note.',
name: 'A Test Level',
data: '4000000000\n0000000000\n0000000000\n0000000000\n0000000000\n0000000000\n0000000000\n0000000000\n0000000000\n0000000003',
},
headers: {
'content-type': 'application/json',
},
} as unknown as NextApiRequestWithAuth;
await createLevelHandler(req, res);
},
test: async ({ fetch }) => {
const res = await fetch();
const response = await res.json();
expect(response.success).toBe(true);
draftLevelId = response._id;
expect(res.status).toBe(200);
},
});
await testApiHandler({
handler: async (_, res) => {
const req: NextApiRequestWrapper = {
gameId: DEFAULT_GAME_ID,
method: 'GET',
query: {
id: draftLevelId,
},
} as unknown as NextApiRequestWrapper;
await getLevelImageHandler(req, res);
},
test: async ({ fetch }) => {
const res = await fetch();
expect(res.status).toBe(401);
const response = await res.json();
expect(res.headers.get('content-type')).toBe('application/json; charset=utf-8');
expect(response.error).toBe('Level is not published');
},
});
}, 30000);
test('Requesting an image for an invalid id format should 400', async () => {
jest.spyOn(logger, 'error').mockImplementation(() => ({} as Logger));
await testApiHandler({
handler: async (_, res) => {
const req: NextApiRequestWrapper = {
gameId: DEFAULT_GAME_ID,
method: 'GET',
query: {
id: '[home]',
},
} as unknown as NextApiRequestWrapper;
await getLevelImageHandler(req, res);
},
test: async ({ fetch }) => {
const res = await fetch();
expect(res.status).toBe(400);
const response = await res.json();
// expect header to be json
expect(res.headers.get('content-type')).toBe('application/json; charset=utf-8');
expect(response.error).toBe('Invalid query.id');
},
});
}, 30000);*/
});
test('processQueueMessages to generate image...', async () => {
await processQueueMessages();
// Note - we do not generate the image during test since we don't have an actual local server running to run puppet against.
});
});

0 comments on commit 305ffa0

Please sign in to comment.