Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
## <small>1.1.10 (2026-04-21)</small>

* fix: forward mock Content-Type to contract validator (avoids false-positive `MISSING_SCHEMA` for binary mocks)

## <small>1.1.9 (2026-04-15)</small>

* chore: update twd-js to 1.7.1
Expand Down
360 changes: 180 additions & 180 deletions package-lock.json

Large diffs are not rendered by default.

8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "twd-cli",
"version": "1.1.9",
"version": "1.1.10",
"description": "CLI tool for running TWD tests with Puppeteer",
"type": "module",
"main": "src/index.js",
Expand All @@ -23,9 +23,9 @@
"author": "",
"license": "ISC",
"dependencies": {
"openapi-mock-validator": "^0.1.4",
"puppeteer": "^24.41.0",
"twd-js": "^1.7.1"
"openapi-mock-validator": "^0.2.0",
"puppeteer": "^24.42.0",
"twd-js": "^1.7.2"
},
"engines": {
"node": ">=18.0.0"
Expand Down
11 changes: 10 additions & 1 deletion src/contracts.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,14 @@ import fs from 'fs';
import path from 'path';
import { OpenAPIMockValidator } from 'openapi-mock-validator';

function readContentType(responseHeaders) {
if (!responseHeaders) return 'application/json';
for (const [key, value] of Object.entries(responseHeaders)) {
if (key.toLowerCase() === 'content-type') return value;
}
return 'application/json';
}

export async function loadContracts(contracts, workingDir) {
const loaded = [];

Expand Down Expand Up @@ -67,12 +75,13 @@ export function validateMocks(collectedMocks, contracts) {
continue;
}

const contentType = readContentType(mock.responseHeaders);
const validation = contract.validator.validateResponse(
pathMatch.path,
mock.method,
mock.status,
mock.response,
{ strict: contract.strict },
{ strict: contract.strict, contentType },
);

results.push({
Expand Down
23 changes: 23 additions & 0 deletions test-example-app/contracts/products-3.0.json
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,29 @@
}
}
},
"/products/{productId}/thumbnail": {
"get": {
"operationId": "getProductThumbnail",
"parameters": [
{
"name": "productId",
"in": "path",
"required": true,
"schema": { "type": "string", "format": "uuid" }
}
],
"responses": {
"200": {
"description": "Product thumbnail image",
"content": {
"image/*": {
"schema": { "type": "string", "format": "binary" }
}
}
}
}
}
},
"/settings": {
"get": {
"operationId": "getSettings",
Expand Down
16 changes: 8 additions & 8 deletions test-example-app/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion test-example-app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.1",
"babel-plugin-react-compiler": "^1.0.0",
"twd-js": "^1.6.5",
"twd-js": "^1.7.2",
"typescript": "~6.0.2",
"vite": "^8.0.3"
}
Expand Down
43 changes: 43 additions & 0 deletions test-example-app/src/App.twd.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -897,3 +897,46 @@ describe("Contract Validation - Events Mismatches (OpenAPI 3.1 — error mode)",
});
});
});

// ── Content-Type forwarding — binary mocks vs image/* spec ───────────

describe("Contract Validation - Content-Type forwarding (Products API)", () => {
it("should match image/png mock against image/* spec entry", async () => {
twd.mockRequest("getProductThumbnailPng", {
method: "GET",
url: "/api/products/550e8400-e29b-41d4-a716-446655440000/thumbnail",
status: 200,
response: "fake-png-bytes",
responseHeaders: { "Content-Type": "image/png" },
});
});

it("should match image/jpeg mock against image/* spec entry", async () => {
twd.mockRequest("getProductThumbnailJpeg", {
method: "GET",
url: "/api/products/550e8400-e29b-41d4-a716-446655440001/thumbnail",
status: 200,
response: "fake-jpeg-bytes",
responseHeaders: { "content-type": "image/jpeg" },
});
});

it("should warn when non-binary Content-Type has no matching spec entry", async () => {
twd.mockRequest("getProductsAsXml", {
method: "GET",
url: "/api/products",
status: 200,
response: "<products></products>",
responseHeaders: { "Content-Type": "application/xml" },
});
});

it("should warn when mock has no responseHeaders against image-only endpoint", async () => {
twd.mockRequest("getProductThumbnailNoHeader", {
method: "GET",
url: "/api/products/550e8400-e29b-41d4-a716-446655440002/thumbnail",
status: 200,
response: "fake-bytes",
});
});
});
93 changes: 93 additions & 0 deletions tests/contracts.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -256,3 +256,96 @@ describe('validateMocks with testId and occurrence', () => {
expect(output.results[1].validation.valid).toBe(true);
});
});

describe('validateMocks — Content-Type forwarding', () => {
let loadedContracts;

beforeEach(async () => {
loadedContracts = await loadContracts(
[{ source: './tests/fixtures/petstore-3.0.json', baseUrl: '/api' }],
path.resolve(__dirname, '..'),
);
});

it('forwards Content-Type from responseHeaders so image/* endpoints match', () => {
const mocks = new Map();
mocks.set('getPetPhoto', {
alias: 'getPetPhoto',
url: '/api/v1/pets/123/photo',
method: 'GET',
status: 200,
response: 'fake-binary-data',
urlRegex: false,
responseHeaders: { 'Content-Type': 'image/png' },
});

const output = validateMocks(mocks, loadedContracts);

expect(output.results).toHaveLength(1);
const missingSchema = output.results[0].validation.warnings.filter(
w => w.type === 'MISSING_SCHEMA'
);
expect(missingSchema).toHaveLength(0);
expect(output.results[0].validation.errors).toHaveLength(0);
});

it('resolves Content-Type when header key is lowercase', () => {
const mocks = new Map();
mocks.set('getPetPhoto', {
alias: 'getPetPhoto',
url: '/api/v1/pets/123/photo',
method: 'GET',
status: 200,
response: 'fake-binary-data',
urlRegex: false,
responseHeaders: { 'content-type': 'image/png' },
});
const output = validateMocks(mocks, loadedContracts);
expect(output.results[0].validation.warnings.some(w => w.type === 'MISSING_SCHEMA')).toBe(false);
});

it('resolves Content-Type when header key is upper-case', () => {
const mocks = new Map();
mocks.set('getPetPhoto', {
alias: 'getPetPhoto',
url: '/api/v1/pets/123/photo',
method: 'GET',
status: 200,
response: 'fake-binary-data',
urlRegex: false,
responseHeaders: { 'CONTENT-TYPE': 'image/png' },
});
const output = validateMocks(mocks, loadedContracts);
expect(output.results[0].validation.warnings.some(w => w.type === 'MISSING_SCHEMA')).toBe(false);
});

it('defaults to application/json when responseHeaders is missing', () => {
const mocks = new Map();
mocks.set('getPets', {
alias: 'getPets',
url: '/api/v1/pets',
method: 'GET',
status: 200,
response: [{ id: 1, name: 'Fido' }],
urlRegex: false,
});
const output = validateMocks(mocks, loadedContracts);
expect(output.results[0].validation.valid).toBe(true);
expect(output.results[0].validation.errors).toHaveLength(0);
});

it('defaults to application/json when responseHeaders has no Content-Type entry', () => {
const mocks = new Map();
mocks.set('getPets', {
alias: 'getPets',
url: '/api/v1/pets',
method: 'GET',
status: 200,
response: [{ id: 1, name: 'Fido' }],
urlRegex: false,
responseHeaders: { 'X-Request-Id': 'abc123' },
});
const output = validateMocks(mocks, loadedContracts);
expect(output.results[0].validation.valid).toBe(true);
});
});
22 changes: 22 additions & 0 deletions tests/fixtures/petstore-3.0.json
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,28 @@
}
}
}
},
"/v1/pets/{petId}/photo": {
"get": {
"parameters": [
{
"name": "petId",
"in": "path",
"required": true,
"schema": { "type": "string" }
}
],
"responses": {
"200": {
"description": "Pet photo",
"content": {
"image/*": {
"schema": { "type": "string", "format": "binary" }
}
}
}
}
}
}
}
}
53 changes: 53 additions & 0 deletions tests/runTests.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -191,4 +191,57 @@ describe("runTests", () => {

expect(result).toBe(true);
});

it("preserves responseHeaders through the __twdCollectMock spread", async () => {
const testStatus = [{ id: 't-1', status: 'pass' }];
const handlers = [{ id: 't-1', name: 'test1', type: 'test' }];

const page = {
goto: vi.fn(),
waitForSelector: vi.fn(),
exposeFunction: vi.fn(),
// Drive the registered __twdCollectMock callback from inside page.evaluate,
// mirroring how a real browser test would trigger it.
evaluate: vi.fn().mockImplementation(async () => {
const exposed = page.exposeFunction.mock.calls.find(
(c) => c[0] === '__twdCollectMock'
);
expect(exposed).toBeDefined();
const collectMock = exposed[1];
await collectMock({
alias: 'getPhoto',
url: '/v1/photo',
method: 'GET',
status: 200,
response: 'bin',
testId: 't-1',
responseHeaders: { 'Content-Type': 'image/png' },
});
return { handlers, testStatus };
}),
};
const browser = createMockBrowser(page);
vi.mocked(puppeteer.launch).mockResolvedValue(browser);
vi.mocked(loadConfig).mockReturnValue({
...defaultMockConfig,
contracts: [{ source: './openapi.json' }],
});
vi.mocked(loadContracts).mockResolvedValue([{ /* sentinel contract */ }]);

let capturedMocks;
vi.mocked(validateMocks).mockImplementation((mocks) => {
capturedMocks = mocks;
return { results: [], skipped: [] };
});
vi.mocked(printContractReport).mockReturnValue(false);

await runTests();

expect(capturedMocks).toBeDefined();
const entries = Array.from(capturedMocks.values());
expect(entries).toHaveLength(1);
expect(entries[0].responseHeaders).toEqual({ 'Content-Type': 'image/png' });
expect(entries[0].alias).toBe('getPhoto');
expect(entries[0].occurrence).toBe(1);
});
});
Loading