Add custom message to Jest expects
Overall
score
99%
Build a test suite for an API response handler that processes data from multiple external services. The handler returns structured response objects that need to be validated against expected patterns. Your tests should verify the response structure and content using flexible pattern matching that checks types and partial content without requiring exact value matches.
Provides enhanced assertion messaging for Jest tests.
Create a module api-handler.js that exports a processApiResponse function:
function processApiResponse(apiName, rawData) {
const timestamp = Date.now();
return {
source: apiName,
timestamp: timestamp,
data: rawData,
metadata: {
processedAt: new Date().toISOString(),
version: "1.0"
}
};
}
module.exports = { processApiResponse };Create a test file api-handler.test.js with tests that verify the response structure using flexible pattern matching:
Response Structure Test: Verify that the processed response has the correct shape with appropriate types for each field, without hardcoding specific timestamp or date values.
Partial Data Matching: Test that the response contains expected data properties while allowing additional properties to exist.
Array Content Validation: When the raw data includes arrays, verify they contain elements of the expected types.
Nested Object Patterns: Test that nested objects (like metadata) match expected patterns with correct property types.
Input:
const response = processApiResponse("weather-api", { temp: 72, conditions: "sunny" });Expected Output: Response should match pattern:
{
source: "weather-api",
timestamp: <any number>,
data: { temp: 72, conditions: "sunny" },
metadata: {
processedAt: <any string>,
version: "1.0"
}
}Input:
const response = processApiResponse("users-api", {
users: [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" }
]
});Expected Output:
Input:
const response = processApiResponse("products-api", {
productId: 101,
name: "Widget",
price: 29.99,
inStock: true
});Expected Output:
productId (number) and name (string)Input:
const response = processApiResponse("orders-api", { orderId: 5001 });Expected Output:
processedAt as a string and version as "1.0"Install with Tessl CLI
npx tessl i tessl/npm-jest-expect-messagedocs
evals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10