### Install sdtt CLI Tool Source: https://github.com/iaincollins/structured-data-testing-tool/blob/master/README.md Installs the structured-data-testing-tool as a global command-line interface (CLI) package using npm. This command makes the `sdtt` executable available system-wide for immediate use. ```bash npm i structured-data-testing-tool -g ``` -------------------------------- ### sdtt CLI Usage Examples Source: https://github.com/iaincollins/structured-data-testing-tool/blob/master/README.md Demonstrates various ways to use the `sdtt` command-line tool to inspect structured data. It covers testing URLs, local files, applying presets, and specifying schemas. Options for outputting results and listing available presets/schemas are also shown. ```bash sdtt --url "https://example.com/article" ``` ```bash sdtt --url --presets SocialMedia ``` ```bash sdtt --url --presets Google ``` ```bash sdtt --url --presets "Twitter,Facebook" ``` ```bash sdtt --url -p Twitter -p Facebook ``` ```bash sdtt --url --schemas Article ``` ```bash sdtt --url --schemas "jsonld:Article" ``` ```bash sdtt --url --schemas "microdata:Article" ``` ```bash sdtt --url --schemas "rdfa:Article" ``` ```bash sdtt --url --schemas "Article,WPHeader,WPFooter" ``` ```bash sdtt --url -s Article -s WPHeader -s WPFooter ``` ```bash sdtt --url --output results.json ``` ```bash sdtt --file .html ``` ```bash sdtt --file .json ``` ```bash sdtt --presets ``` ```bash sdtt --schemas ``` -------------------------------- ### Microdata Article Schema Source: https://github.com/iaincollins/structured-data-testing-tool/blob/master/__tests__/fixtures/example.html Demonstrates the use of Microdata to mark up an article with schema.org types. This helps search engines understand the content's context, including author and publication date. ```html

Example Headline in Microdata

``` -------------------------------- ### CLI Example Output for URL Testing Source: https://github.com/iaincollins/structured-data-testing-tool/blob/master/README.md This snippet shows the typical output from the Structured Data Testing Tool CLI when testing a URL with Google and SocialMedia presets. It details the tests performed, the pass/fail status, and a summary of statistics. ```text $ sdtt --url https://www.bbc.co.uk/news/world-us-canada-49060410 --presets Google,SocialMedia Tests Schema.org > ReportageNewsArticle - 100% (1 passed, 0 failed) ✓ schema in jsonld • @context • @type • url • publisher.@type • publisher.name • publisher.publishingPrinciples • publisher.logo.@type • publisher.logo.url • datePublished • dateModified • headline • image.@type • image.width • image.height • image.url • thumbnailUrl • author.@type • author.name • author.logo.@type • author.logo.url • author.noBylinesPolicy • mainEntityOfPage • video.@list[0].@type • video.@list[0].name • video.@list[0].description • video.@list[0].duration • video.@list[0].thumbnailUrl • video.@list[0].uploadDate • video.@list[1].@type • video.@list[1].name • video.@list[1].description • video.@list[1].duration • video.@list[1].thumbnailUrl • video.@list[1].uploadDate Google > ReportageNewsArticle > #0 (jsonld) - 100% (12 passed, 0 failed) ✓ ReportageNewsArticle ✓ @type ✓ author ✓ datePublished ✓ headline ✓ image ✓ publisher.@type ✓ publisher.name ✓ publisher.logo ✓ publisher.logo.url ✓ dateModified ✓ mainEntityOfPage Facebook - 100% (8 passed, 0 failed) ✓ must have page title ✓ must have page type ✓ must have url ✓ must have image url ✓ must have image alt text ✓ should have page description ✓ should have account username ✓ should have locale Twitter - 100% (7 passed, 0 failed) ✓ must have card type ✓ must have title ✓ must have description ✓ must have image url ✓ must have image alt text ✓ should have account username ✓ should have username of content creator Statistics Number of Metatags: 38 Schemas in JSON-LD: 1 Schemas in HTML: 0 Schema in RDFa: 0 Schema.org schemas: ReportageNewsArticle Other schemas: 0 Test groups run: 5 Optional tests run: 71 Pass/Fail tests run: 28 Results Passed: 28 (100%) Warnings: 0 (0%) Failed: 0 (0%) ✓ 28 tests passed with 0 warnings. Use the option '-i' to display additional detail. ``` -------------------------------- ### JSON-LD Article Schema Source: https://github.com/iaincollins/structured-data-testing-tool/blob/master/__tests__/fixtures/example.html Provides an example of JSON-LD used to describe an article, adhering to schema.org vocabulary. JSON-LD is a method of encoding Linked Data using JSON, often placed in a script tag. ```json { "@context": "http://schema.org", "@type": "ReportageNewsArticle", "headline": "Example Headline in JSON-LD", "author": "C Smith", "url": "http://example.com/path-to-article", "image": "http://example.com/path-to-article-image.jpg", "datePublished": "2019-01-01", "publisher": { "@type": "Organization", "name": "ACME News", "logo": { "@type": "ImageObject", "url": "https://www.example.com/logo.png" } } } ``` -------------------------------- ### Custom Presets for Reusable Validation - JavaScript Source: https://context7.com/iaincollins/structured-data-testing-tool/llms.txt Demonstrates creating and using custom presets for structured data validation. Presets are reusable collections of tests that can be named, described, and conditionally applied. This example shows how to define a preset, include other presets within a new one, and apply them to a URL using the `structuredDataTest` function. Results are grouped by preset. ```javascript const { structuredDataTest } = require('structured-data-testing-tool'); // Define custom preset const MyArticlePreset = { name: 'My Article Tests', description: 'Custom validation for article pages', url: 'https://docs.example.com/article-requirements', schema: 'Article', conditional: { test: 'Article', // Only run if Article schema exists }, tests: [ { test: 'Article[*]."@type"', expect: 'Article' }, { test: 'Article[*].headline', expect: true }, { test: 'Article[*].author', expect: true }, { test: 'Article[*].datePublished', expect: true }, { test: 'Article[*].image', expect: true }, { test: 'Article[*].publisher.name', expect: true }, { test: 'Article[*].publisher.logo', expect: true }, { test: 'Article[*].wordCount', expect: true, warning: true }, ] }; // Preset that includes other presets const ComprehensivePreset = { name: 'Comprehensive Tests', description: 'Run all custom and built-in tests', presets: [MyArticlePreset], // Include other presets tests: [ { test: '"og:title"', type: 'metatag' }, { test: '"og:description"', type: 'metatag' } ] }; // Conditional preset (runs only if condition passes) const VideoPreset = { name: 'Video Tests', description: 'Validation for pages with video', conditional: { test: 'VideoObject', // Only run if VideoObject exists }, tests: [ { test: 'VideoObject[*].name', expect: true }, { test: 'VideoObject[*].description', expect: true }, { test: 'VideoObject[*].thumbnailUrl', expect: true }, { test: 'VideoObject[*].uploadDate', expect: true }, { test: 'VideoObject[*].duration', expect: /^PT/, description: 'duration must be ISO 8601 format' } ] }; // Use custom presets structuredDataTest('https://example.com/article', { presets: [MyArticlePreset, ComprehensivePreset, VideoPreset], schemas: ['Article'] }) .then(res => { console.log('All preset tests passed'); // Group results by preset const groupedResults = {}; res.tests.forEach(test => { const group = test.groups ? test.groups[0] : 'Other'; if (!groupedResults[group]) groupedResults[group] = []; groupedResults[group].push(test); }); Object.keys(groupedResults).forEach(group => { console.log(` ${group}:`); groupedResults[group].forEach(test => { console.log(` ${test.passed ? '✓' : '✗'} ${test.description || test.test}`); }); }); }) .catch(err => { console.log('Validation failed'); }); ``` -------------------------------- ### API: Test HTML content directly Source: https://context7.com/iaincollins/structured-data-testing-tool/llms.txt JavaScript examples demonstrating how to use the 'structuredDataTest' function to validate HTML content provided as a string, a file buffer, or a readable stream. This bypasses the need to fetch content from a URL. ```javascript const { structuredDataTest } = require('structured-data-testing-tool'); const fs = require('fs'); // From HTML string const html = ` `; structuredDataTest(html, { schemas: ['Article'] }) .then(res => { console.log('Valid Article schema found'); console.log('Article data:', res.structuredData.jsonld.Article[0]); }) .catch(err => { console.log('Validation failed'); }); // From file buffer const fileBuffer = fs.readFileSync('./example.html'); structuredDataTest(fileBuffer, { schemas: ['Article'] }) .then(res => console.log('File validated successfully')) .catch(err => console.log('Validation failed')); // From readable stream const stream = fs.createReadStream('./example.html'); structuredDataTest(stream, { schemas: ['Article'] }) .then(res => console.log('Stream validated successfully')) .catch(err => console.log('Validation failed')); ``` -------------------------------- ### RDFa Article Schema Source: https://github.com/iaincollins/structured-data-testing-tool/blob/master/__tests__/fixtures/example.html Illustrates how to use RDFa attributes to embed structured data within HTML for an article. This approach is similar to Microdata in providing semantic meaning to web content for machines. ```html

Example Headline in RDFa

B Smith
``` -------------------------------- ### Define Custom Presets for Reusable Tests (JavaScript) Source: https://github.com/iaincollins/structured-data-testing-tool/blob/master/README.md This example shows how to create a custom preset object named 'MyCustomPreset' which includes a name, description, and an array of tests. This preset can then be included in the 'presets' option when calling the structuredDataTest function. It also illustrates optional preset properties like 'group', 'schema', 'presets', and 'conditional'. ```javascript const url = 'https://www.bbc.co.uk/news/world-us-canada-49060410' // This test shows how you can use different types of tests in one preset. const MyCustomPreset = { name: 'My Custom Preset', // Required description: 'Test ReportageNewsArticle JSON-LD data is defined and twitter metadata was found', // Required tests: [ // Required (unless 'presets' is specified) { test: 'ReportageNewsArticle', type: 'jsonld' }, { test: '"twitter:card"', type: 'metatag' }, // Corrected syntax for string literal in test { test: '"twitter:domain"', expect: 'www.bbc.co.uk', type: 'metatag', } ], // Additional options you can use in a preset: // group: 'My Group Name', // A group name can be used to group tests in a preset (defaults to preset name) // schema: 'NewsArticle', // Specify a schema at the top level if all the tests in the preset apply to the same schema // presets: [] // A preset can also invoke other presets, making it easy to re-use custom tests // conditional: {} // Define a conditional `test`, which is evaluated to determine if the preset should run } const options = { // The 'presets' argument should be an array of preset objects presets: [ MyCustomPreset ], // If you just want to detect a schema exists, you can populate the // the 'schemas' option with a list of schema names (as strings). schemas: [ 'ReportageNewsArticle' ], // By default, any structured data detected will automatically be tested. // Set 'auto' to 'false' if you want to disable this (defaults to 'true'). // This may mean you miss some errors, but make make debugging easier. auto: false } structuredDataTest(url, options) .then(response => { /* … */ }) .catch(err => { /* … */ }) ``` -------------------------------- ### Testing with Client-Side Rendering using Puppeteer and structured-data-testing-tool Source: https://github.com/iaincollins/structured-data-testing-tool/blob/master/README.md This snippet demonstrates how to test web pages that use client-side rendering (JavaScript) with the structured-data-testing-tool. It uses Puppeteer to launch a headless Chrome instance, navigate to a URL, fetch the rendered HTML, and then passes this HTML to the structuredDataTest function. This is useful for pages that inject structured data via JavaScript, such as through Google Tag Manager. Puppeteer must be installed separately and is only usable with the API. ```javascript const { structuredDataTest } = require('structured-data-testing-tool') const puppeteer = require('puppeteer'); (async () => { const url = 'https://www.bbc.co.uk/news/world-us-canada-49060410' const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto(url, { waitUntil: 'networkidle2' }); const html = await page.evaluate(() => document.body.innerHTML); await browser.close(); await structuredDataTest(html) .then(response => { console.log("All tests passed.") }) .catch(err => { console.log("Some tests failed.") }) })(); ``` -------------------------------- ### CLI: List available presets and schemas Source: https://context7.com/iaincollins/structured-data-testing-tool/llms.txt Command-line interface commands to list all available built-in testing presets and supported Schema.org schemas. This helps users understand the tool's capabilities. ```bash # List all built-in presets sdtt --presets # List all supported Schema.org schemas sdtt --schemas ``` -------------------------------- ### sdtt CLI List Presets/Schemas Source: https://github.com/iaincollins/structured-data-testing-tool/blob/master/README.md Shows the commands for listing all available built-in presets and supported schemas within the `sdtt` tool. This is useful for understanding the testing capabilities and options available. ```bash sdtt --presets ``` ```bash sdtt --schemas ``` -------------------------------- ### sdtt CLI Basic Usage Source: https://github.com/iaincollins/structured-data-testing-tool/blob/master/README.md Provides the fundamental commands for using the `sdtt` CLI tool to inspect either a live URL or a local file. These commands initiate the structured data analysis process. ```bash sdtt --url ``` ```bash sdtt --file ``` -------------------------------- ### Run Structured Data Tests with Advanced Options Source: https://context7.com/iaincollins/structured-data-testing-tool/llms.txt Demonstrates how to configure and run structured data tests using the 'structured-data-testing-tool' with advanced options. It includes setting presets, specifying schemas, disabling auto-detection, defining custom test assertions with expected values and conditions, and handling the response object to access test results, schema types, and detailed error information. ```javascript const { structuredDataTest } = require('structured-data-testing-tool'); const { Google } = require('structured-data-testing-tool/presets'); const options = { presets: [Google], schemas: ['Article', 'Organization'], // Disable auto-detection of schemas (only test explicitly specified schemas) auto: false, tests: [ { test: 'Article[*].headline', expect: /^.{10,110}$/, // Headline should be 10-110 characters description: 'headline length should be 10-110 characters' }, { test: 'Article[*].image', expect: true, group: 'Images', // Custom grouping for results description: 'must have article image' }, { test: 'Article[*].wordCount', optional: true, // Optional test (doesn't count as pass/fail) description: 'may have word count' }, { test: 'Article[*].reviewedBy', conditional: { // Only run if Article.reviewRating exists test: 'Article[*].reviewRating' }, description: 'reviewed articles must have reviewer' } ] }; structuredDataTest('https://example.com/article', options) .then(res => { // Response structure console.log('Passed tests:', res.passed.length); console.log('Failed tests:', res.failed.length); console.log('Warnings:', res.warnings.length); console.log('Optional tests:', res.optional.length); console.log('Skipped tests:', res.skipped.length); console.log('Schemas found:', res.schemas); console.log('Test groups:', res.groups); // Structured data by type console.log('JSON-LD schemas:', Object.keys(res.structuredData.jsonld)); console.log('Microdata schemas:', Object.keys(res.structuredData.microdata)); console.log('RDFa schemas:', Object.keys(res.structuredData.rdfa)); console.log('Meta tags:', Object.keys(res.structuredData.metatags)); // Detailed test results res.passed.forEach(test => { console.log(`✓ ${test.description || test.test}`); console.log(` Type: ${test.type}`); console.log(` Value: ${test.value}`); if (test.schema) console.log(` Schema: ${test.schema}`); if (test.url) console.log(` Docs: ${test.url}`); }); // Access original options console.log('Test options used:', res.options); }) .catch(err => { if (err.type === 'VALIDATION_FAILED') { const res = err.res; // Failed tests with error details res.failed.forEach(test => { console.log(`✗ ${test.description || test.test}`); if (test.error) { console.log(` Error type: ${test.error.type}`); console.log(` Message: ${test.error.message}`); if (test.error.expected) console.log(` Expected: ${test.error.expected}`); if (test.error.found) console.log(` Found: ${test.error.found}`); } }); // Warnings (soft failures) res.warnings.forEach(test => { console.log(`⚠ ${test.description || test.test}`); }); } }); ``` -------------------------------- ### CLI: Test URL for all structured data Source: https://context7.com/iaincollins/structured-data-testing-tool/llms.txt Command-line interface command to test a given URL for all supported structured data formats. No external dependencies are required beyond the CLI tool itself. ```bash sdtt --url "https://www.bbc.co.uk/news/world-us-canada-49060410" ``` -------------------------------- ### CLI: Test URL with built-in presets Source: https://context7.com/iaincollins/structured-data-testing-tool/llms.txt Command-line interface command to test a URL against specific built-in testing presets like Google, Twitter, or Facebook. This is useful for ensuring compliance with platform-specific recommendations. ```bash # Test for Google, Twitter, Facebook compliance sdtt --url "https://example.com/article" --presets "Google,Twitter,Facebook" # Multiple preset syntax (alternative) sdtt --url "https://example.com" -p Twitter -p Facebook ``` -------------------------------- ### CLI: Test for specific Schema.org schemas Source: https://context7.com/iaincollins/structured-data-testing-tool/llms.txt Command-line interface command to test a URL for specific Schema.org schemas, with options to specify the format (e.g., JSON-LD, Microdata) or test for multiple schemas simultaneously. ```bash # Test for Article schema in any format sdtt --url "https://example.com/article" --schemas Article # Test for Article in JSON-LD specifically sdtt --url "https://example.com" --schemas "jsonld:Article" # Test for Article in Microdata sdtt --url "https://example.com" --schemas "microdata:Article" # Test for multiple schemas sdtt --url "https://example.com" --schemas "Article,Organization,WebPage" ``` -------------------------------- ### CLI: Test local files Source: https://context7.com/iaincollins/structured-data-testing-tool/llms.txt Command-line interface command to test structured data from local files, supporting both HTML files and specific structured data files like JSON-LD. Requires the file path as an argument. ```bash # Test HTML file sdtt --file ./page.html --presets Google # Test JSON-LD file sdtt --file ./structured-data.json --schemas Article ``` -------------------------------- ### API - Test URL with Presets and Schemas (JavaScript) Source: https://github.com/iaincollins/structured-data-testing-tool/blob/master/README.md Demonstrates how to use the Structured Data Testing Tool API in Node.js to test a URL. It shows how to specify multiple presets (Google, Twitter, Facebook) and a specific schema (ReportageNewsArticle). Error handling for validation failures is included. ```javascript const { structuredDataTest } = require('structured-data-testing-tool') const { Google, Twitter, Facebook } = require('structured-data-testing-tool/presets') const url = 'https://www.bbc.co.uk/news/world-us-canada-49060410' let result structuredDataTest(url, { // Check for compliance with Google, Twitter and Facebook recommendations presets: [ Google, Twitter, Facebook ], // Check the page includes a specific Schema (see https://schema.org/docs/full.html for a list) schemas: [ 'ReportageNewsArticle' ] }) .then(res => { console.log('✅ All tests passed!') result = res }) .catch(err => { if (err.type === 'VALIDATION_FAILED') { console.log('❌ Some tests failed.') result = err.res } else { console.log(err) // Handle other errors here (e.g. an error fetching a URL) } }) .finally(() => { if (result) { console.log( `Passed: ${result.passed.length},`, `Failed: ${result.failed.length},`, `Warnings: ${result.warnings.length}`, ) console.log(`Schemas found: ${result.schemas.join(',')}`) // Loop over validation errors if (result.failed.length > 0) console.log("⚠️ Errors:\n", result.failed.map(test => test)) } }) ``` -------------------------------- ### sdtt CLI Preset and Schema Testing Source: https://github.com/iaincollins/structured-data-testing-tool/blob/master/README.md Illustrates how to use the `sdtt` CLI tool to test for specific structured data presets or schemas. This allows for targeted validation of particular types of markup, such as social media tags or specific Schema.org types. ```bash sdtt --url --presets "Twitter,Facebook" ``` ```bash sdtt --url --schemas "Article" ``` ```bash sdtt --url --schemas "jsonld:Article,microdata:Article" ``` -------------------------------- ### ClaimReview Schema Preset for Structured Data Testing Source: https://github.com/iaincollins/structured-data-testing-tool/blob/master/README.md A JavaScript preset designed to automatically test all instances of the ClaimReview schema found on a page. It uses JMESPath queries to validate specific properties and includes optional warnings for less critical checks. This preset is particularly useful for pages with multiple ClaimReview schema instances. ```javascript const ClaimReview = { name: 'ClaimReview', description: 'A fact-checking review of claims made (or reported) in some creative work (referenced via itemReviewed).', // If you add 'schema' property to a preset **and** write tests that start with a selector like `ClaimReview[*]` // (i.e. with the schema name followed by an asterisk in the selector) then those tests will automatically // be run against every instance of that schema found, so you can easily find where an error is if there are // multiple instances of the same schema on a page. schema: 'ClaimReview', // A 'conditional' on a preset or test is just a normal test object. If it fails to pass, the tests in the // preset (or the individual test, if it is used on a test) will not be run. conditional: { test: 'ClaimReview' }, tests: [ // Expected by Google { test: `ClaimReview` }, { test: `ClaimReview[*]."@type"`, expect: 'ClaimReview' }, { test: `ClaimReview[*].url` }, { test: `ClaimReview[*].reviewRating` }, { test: `ClaimReview[*].claimReviewed` }, // Warnings { test: `ClaimReview[*].author`, warning: true }, { test: `ClaimReview[*].datePublished`, warning: true }, { test: `ClaimReview[*].itemReviewed`, warning: true }, ], } module.exports = { ClaimReview } ``` -------------------------------- ### API: Test URL with presets and schemas Source: https://context7.com/iaincollins/structured-data-testing-tool/llms.txt JavaScript function to test a URL for structured data validation using the 'structured-data-testing-tool' library. It accepts presets and specific schemas, and handles promise-based results for success and validation failures. ```javascript const { structuredDataTest } = require('structured-data-testing-tool'); const { Google, Twitter, Facebook } = require('structured-data-testing-tool/presets'); const url = 'https://www.bbc.co.uk/news/world-us-canada-49060410'; structuredDataTest(url, { presets: [Google, Twitter, Facebook], schemas: ['ReportageNewsArticle'] }) .then(res => { console.log('✅ All tests passed!'); console.log(`Passed: ${res.passed.length}`); console.log(`Warnings: ${res.warnings.length}`); console.log(`Schemas found: ${res.schemas.join(', ')}`); // Access structured data console.log('JSON-LD data:', res.structuredData.jsonld); console.log('Microdata:', res.structuredData.microdata); console.log('Meta tags:', res.structuredData.metatags); }) .catch(err => { if (err.type === 'VALIDATION_FAILED') { console.log('❌ Some tests failed'); console.log(`Failed: ${err.res.failed.length}`); // Inspect failures err.res.failed.forEach(test => { console.log(`- ${test.description || test.test}`); if (test.error) { console.log(` Expected: ${test.expect}`); console.log(` Found: ${test.error.found || 'not found'}`); } }); } else { console.error('Error fetching URL:', err); } }); ``` -------------------------------- ### Test HTML from string, file buffer, or stream Source: https://context7.com/iaincollins/structured-data-testing-tool/llms.txt Demonstrates how to use the `structuredDataTest` function with different input types: an HTML string, a file buffer read from a local file, or a readable stream from a local file. ```APIDOC ## Test HTML from string, file buffer, or stream ### Description Tests HTML content directly without fetching from a URL, using an HTML string, a file buffer, or a readable stream. ### Method `structuredDataTest(input, options)` ### Parameters See `structuredDataTest()` API documentation for parameter details. ### Request Example ```javascript const { structuredDataTest } = require('structured-data-testing-tool'); const fs = require('fs'); // From HTML string const html = ` `; structuredDataTest(html, { schemas: ['Article'] }) .then(res => { console.log('Valid Article schema found'); console.log('Article data:', res.structuredData.jsonld.Article[0]); }) .catch(err => { console.log('Validation failed'); }); // From file buffer const fileBuffer = fs.readFileSync('./example.html'); structuredDataTest(fileBuffer, { schemas: ['Article'] }) .then(res => console.log('File validated successfully')) .catch(err => console.log('Validation failed')); // From readable stream const stream = fs.createReadStream('./example.html'); structuredDataTest(stream, { schemas: ['Article'] }) .then(res => console.log('Stream validated successfully')) .catch(err => console.log('Validation failed')); ``` ### Response See `structuredDataTest()` API documentation for response details. ``` -------------------------------- ### API - Test Local HTML File (JavaScript) Source: https://github.com/iaincollins/structured-data-testing-tool/blob/master/README.md Shows how to use the Structured Data Testing Tool API in Node.js to test a local HTML file. The HTML content can be provided as a string, stream, or readable buffer. ```javascript const html = fs.readFileSync('./example.html') structuredDataTest(html) .then(response => { /* … */ }) .catch(err => { /* … */ }) ``` -------------------------------- ### CLI: Output results to file Source: https://context7.com/iaincollins/structured-data-testing-tool/llms.txt Command-line interface command to save the results of a structured data test to a specified JSON file. This is useful for record-keeping or further analysis. ```bash sdtt --url "https://example.com" --presets Google --output results.json ``` -------------------------------- ### Test Client-Side Rendered Structured Data with Puppeteer Source: https://context7.com/iaincollins/structured-data-testing-tool/llms.txt Tests structured data rendered by JavaScript in a headless browser using Puppeteer. It navigates to a URL, waits for content to load, extracts the HTML, and validates it against specified presets and schemas. Requires 'structured-data-testing-tool' and 'puppeteer'. ```javascript const { structuredDataTest } = require('structured-data-testing-tool'); const { Google, Twitter, Facebook } = require('structured-data-testing-tool/presets'); const puppeteer = require('puppeteer'); async function testClientSideRendering() { const url = 'https://example.com/spa-article'; const browser = await puppeteer.launch({ headless: true, args: ['--no-sandbox', '--disable-setuid-sandbox'] }); try { const page = await browser.newPage(); await page.goto(url, { waitUntil: 'networkidle2', timeout: 30000 }); await page.waitForSelector('script[type="application/ld+json"]', { timeout: 5000 }); const html = await page.content(); const result = await structuredDataTest(html, { presets: [Google, Twitter, Facebook], schemas: ['Article'] }); console.log('✅ Client-side rendered structured data is valid'); console.log(`Schemas found: ${result.schemas.join(', ')}`); console.log(`Tests passed: ${result.passed.length}`); return result; } catch (err) { if (err.type === 'VALIDATION_FAILED') { console.log('❌ Validation failed for client-side rendered page'); console.log(`Failed: ${err.res.failed.length}`); err.res.failed.forEach(test => { console.log(` - ${test.description || test.test}`); }); return err.res; } else { throw err; } } finally { await browser.close(); } } testClientSideRendering().then(() => { console.log('Client-side testing complete'); }); ``` -------------------------------- ### Test Local HTML File API Source: https://github.com/iaincollins/structured-data-testing-tool/blob/master/README.md This API endpoint allows you to test the structured data of a local HTML file by providing its content. ```APIDOC ## POST /api/test/html ### Description Tests the structured data of a local HTML file by accepting its content as a string, stream, or readable buffer. ### Method POST ### Endpoint `/api/test/html` ### Parameters #### Request Body - **html** (string | stream | buffer) - Required - The HTML content to test. ### Request Example ```javascript const fs = require('fs'); const html = fs.readFileSync('./example.html'); // Assuming 'structuredDataTest' is imported and configured to use the API structuredDataTest(html) .then(response => { console.log('✅ HTML test passed!'); // Process response }) .catch(err => { console.error('❌ HTML test failed:', err); // Handle errors }); ``` ### Response #### Success Response (200) - **passed** (array) - A list of tests that passed. - **failed** (array) - A list of tests that failed. - **warnings** (array) - A list of warnings generated during testing. - **schemas** (array of strings) - A list of detected schema types. #### Response Example ```json { "passed": [ "ExampleSchema", "@type", "name" ], "failed": [], "warnings": [], "schemas": ["ExampleSchema"] } ``` ``` -------------------------------- ### Test URL API Source: https://github.com/iaincollins/structured-data-testing-tool/blob/master/README.md This API endpoint allows you to test the structured data of a given URL. You can specify presets and schemas to check for compliance. ```APIDOC ## POST /api/test/url ### Description Tests the structured data of a given URL against specified presets and schemas. ### Method POST ### Endpoint `/api/test/url` ### Parameters #### Request Body - **url** (string) - Required - The URL to test. - **presets** (array of strings) - Optional - An array of preset configurations (e.g., ['Google', 'Twitter', 'Facebook']). - **schemas** (array of strings) - Optional - An array of schema types to check for (e.g., ['ReportageNewsArticle']). ### Request Example ```json { "url": "https://www.bbc.co.uk/news/world-us-canada-49060410", "presets": ["Google", "Twitter", "Facebook"], "schemas": ["ReportageNewsArticle"] } ``` ### Response #### Success Response (200) - **passed** (array) - A list of tests that passed. - **failed** (array) - A list of tests that failed. - **warnings** (array) - A list of warnings generated during testing. - **schemas** (array of strings) - A list of detected schema types. #### Response Example ```json { "passed": [ "ReportageNewsArticle", "@type", "url", "publisher.@type", "publisher.name", "publisher.logo.url", "datePublished", "dateModified", "headline", "image.@type", "image.width", "image.height", "image.url", "thumbnailUrl", "author.@type", "author.name", "author.logo.@type", "author.logo.url", "author.noBylinesPolicy", "mainEntityOfPage", "video.@list[0].@type", "video.@list[0].name", "video.@list[0].description", "video.@list[0].duration", "video.@list[0].thumbnailUrl", "video.@list[0].uploadDate", "video.@list[1].@type", "video.@list[1].name", "video.@list[1].description", "video.@list[1].duration", "video.@list[1].thumbnailUrl", "video.@list[1].uploadDate" ], "failed": [], "warnings": [], "schemas": ["ReportageNewsArticle"] } ``` ``` -------------------------------- ### Test Multiple Pages with GTM-Injected Structured Data using Puppeteer Source: https://context7.com/iaincollins/structured-data-testing-tool/llms.txt Tests structured data injected by Google Tag Manager (GTM) across multiple URLs. It launches a browser, visits each URL, waits for GTM to inject data, extracts HTML, and runs validation. Useful for verifying dynamic content injection. ```javascript const { structuredDataTest } = require('structured-data-testing-tool'); const { Google } = require('structured-data-testing-tool/presets'); const puppeteer = require('puppeteer'); async function testMultiplePagesWithGTM() { const urls = [ 'https://example.com/article-1', 'https://example.com/article-2', 'https://example.com/article-3' ]; const browser = await puppeteer.launch({ headless: true }); const results = []; for (const url of urls) { const page = await browser.newPage(); await page.goto(url, { waitUntil: 'networkidle2' }); await page.waitForTimeout(2000); const html = await page.content(); try { const result = await structuredDataTest(html, { presets: [Google], schemas: ['Article'] }); results.push({ url, status: 'passed', tests: result.passed.length }); } catch (err) { if (err.type === 'VALIDATION_FAILED') { results.push({ url, status: 'failed', failed: err.res.failed.length, errors: err.res.failed.map(t => t.description || t.test) }); } } await page.close(); } await browser.close(); console.log('Test Summary:'); results.forEach(r => { console.log(`${r.url}: ${r.status} (${r.tests || r.failed} tests)`); }); return results; } // Example of how to call this function (remove or adapt as needed) // testMultiplePagesWithGTM(); ``` -------------------------------- ### Define Custom Tests for Structured Data Validation (JavaScript) Source: https://github.com/iaincollins/structured-data-testing-tool/blob/master/README.md This snippet demonstrates how to define custom tests using an options object with a 'tests' array. Each test object can specify the query, expected value, type (e.g., 'jsonld', 'metatag'), and whether it should be a warning. It's used with the structuredDataTest function to validate specific properties and values within structured data. ```javascript const testUrl = 'https://www.bbc.co.uk/news/world-us-canada-49060410' const options = { tests: [ // Check 'NewsArticle' schema exists in JSON-LD { test: 'NewsArticle', expect: true, type: 'jsonld' }, // Check a 'NewsArticle' schema exists with 'url' property set to the value of the variable 'url' { test: 'NewsArticle[*].url', expect: testUrl }, // A similar check as above, but won't fail (only warn) if the test doesn't pass { test: 'NewsArticle[*].mainEntityOfPage', expect: testUrl, warning: true }, // Test for a Twitter meta tag with specific value { test: '"twitter:domain"', expect: 'www.bbc.co.uk', type: 'metatag' } // Corrected syntax for string literal in test ] } structuredDataTest(testUrl, options) .then(response => { /* … */ }) .catch(err => { /* … */ }) ``` -------------------------------- ### structuredDataTest() API Source: https://context7.com/iaincollins/structured-data-testing-tool/llms.txt Tests a URL, HTML string, file buffer, or stream for structured data validation. It can accept presets for common testing scenarios (Google, Twitter, Facebook) and specific Schema.org schemas. The function returns a promise that resolves with test results or rejects with validation errors. ```APIDOC ## structuredDataTest() ### Description Tests a URL, HTML string, file buffer, or stream for structured data validation. ### Method `structuredDataTest(input, options)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **input** (string | Buffer | ReadableStream) - The URL of the page to test, or the HTML content as a string, file buffer, or readable stream. - **options** (object) - An optional object for configuring the test. - **presets** (array) - An array of preset configurations (e.g., `[Google, Twitter, Facebook]`). - **schemas** (array) - An array of Schema.org schema names to test for (e.g., `['Article', 'Organization']`). Can be qualified with format (e.g., `['jsonld:Article']`). ### Request Example ```javascript const { structuredDataTest } = require('structured-data-testing-tool'); const { Google, Twitter, Facebook } = require('structured-data-testing-tool/presets'); const url = 'https://www.bbc.co.uk/news/world-us-canada-49060410'; structuredDataTest(url, { presets: [Google, Twitter, Facebook], schemas: ['ReportageNewsArticle'] }) .then(res => { console.log('✅ All tests passed!'); console.log(`Passed: ${res.passed.length}`); console.log(`Warnings: ${res.warnings.length}`); console.log(`Schemas found: ${res.schemas.join(', ')}`); // Access structured data console.log('JSON-LD data:', res.structuredData.jsonld); console.log('Microdata:', res.structuredData.microdata); console.log('Meta tags:', res.structuredData.metatags); }) .catch(err => { if (err.type === 'VALIDATION_FAILED') { console.log('❌ Some tests failed'); console.log(`Failed: ${err.res.failed.length}`); // Inspect failures err.res.failed.forEach(test => { console.log(`- ${test.description || test.test}`); if (test.error) { console.log(` Expected: ${test.expect}`); console.log(` Found: ${test.error.found || 'not found'}`); } }); } else { console.error('Error fetching URL:', err); } }); ``` ### Response #### Success Response (200) An object containing test results: - **passed** (array) - Array of passed tests. - **warnings** (array) - Array of warnings. - **failed** (array) - Array of failed tests. - **schemas** (array) - Array of detected schema names. - **structuredData** (object) - Object containing the extracted structured data (jsonld, microdata, metatags). #### Response Example ```json { "passed": [...], "warnings": [...], "failed": [], "schemas": ["Article"], "structuredData": { "jsonld": { "Article": [ { "@context": "https://schema.org", "@type": "Article", "headline": "Example Article" } ] }, "microdata": null, "metatags": { "twitter:card": "summary", "og:title": "Example Article" } } } ``` #### Error Response (VALIDATION_FAILED) An object containing validation failure details: - **type** (string) - Set to 'VALIDATION_FAILED'. - **res** (object) - Contains details about the failed tests. - **failed** (array) - Array of failed test objects, each with properties like `description`, `test`, `expect`, and `error`. #### Error Response Example ```json { "type": "VALIDATION_FAILED", "res": { "failed": [ { "description": "Missing required property 'headline'", "test": "required", "expect": "headline", "error": { "found": null } } ] } } ``` ```