CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl-labs/jest-testing

Jest testing patterns — test structure, mocking, async testing, snapshot

99

1.26x
Quality

99%

Does it follow best practices?

Impact

99%

1.26x

Average score across 6 eval scenarios

SecuritybySnyk

Passed

No known issues

Overview
Quality
Evals
Security
Files

task.mdevals/scenario-2/

Write Tests for the Inventory API

Problem/Feature Description

The e-commerce platform has an inventory management API built with Express. The /api/products endpoint supports listing all products and creating new ones. It delegates all database operations to a ProductRepository class that communicates with a PostgreSQL database.

Before the upcoming product launch, the team needs a test suite for the API layer that can run in CI without a real database. The tests should validate correct request handling, proper response formats, and graceful error handling when the database is unavailable or returns unexpected results.

Output Specification

Write a complete Jest test file at src/api/__tests__/products.test.ts.

Tests should cover at minimum:

  • GET /api/products returns a list of products with status 200
  • GET /api/products returns an empty array when no products exist
  • POST /api/products creates a product and returns it with status 201
  • POST /api/products returns 400 when required fields are missing
  • Appropriate error handling when the repository throws an unexpected error

Input Files

src/api/productsRouter.ts

import { Router, Request, Response } from 'express';
import { ProductRepository } from '../db/productRepository';

const router = Router();
const repo = new ProductRepository();

router.get('/products', async (req: Request, res: Response) => {
  try {
    const products = await repo.findAll();
    res.status(200).json({ data: products });
  } catch (err) {
    res.status(500).json({ error: 'Internal server error' });
  }
});

router.post('/products', async (req: Request, res: Response) => {
  const { name, price, stock } = req.body;
  if (!name || price === undefined || stock === undefined) {
    return res.status(400).json({ error: 'name, price, and stock are required' });
  }
  try {
    const product = await repo.create({ name, price, stock });
    res.status(201).json({ data: product });
  } catch (err) {
    res.status(500).json({ error: 'Internal server error' });
  }
});

export default router;

src/app.ts

import express from 'express';
import productsRouter from './api/productsRouter';

export const app = express();
app.use(express.json());
app.use('/api', productsRouter);

src/db/productRepository.ts

export interface Product {
  id: number;
  name: string;
  price: number;
  stock: number;
}

export class ProductRepository {
  async findAll(): Promise<Product[]> {
    throw new Error('Not implemented');
  }

  async create(data: Omit<Product, 'id'>): Promise<Product> {
    throw new Error('Not implemented');
  }
}

evals

tile.json