Skip to main content

Mock Data for Preview

Mock data allows you to preview and test your Myop component without a host application. This is essential for development, documentation, and demos.

Basic Setup​

Add a special script tag with id="myop_preview" at the end of your component:

<script id="myop_preview">
setTimeout(() => {
window.myop_init_interface({
components: [
{
id: "comp-id-0",
name: "AuthService",
developerName: "Alice Green",
lastEditedDate: "2024-03-15T10:30:00.000Z",
lastVersionName: "v1.2.3",
environments: ["prod"],
tags: ["backend", "security"]
}
]
});
});
</script>

Why setTimeout?​

The setTimeout() is used to simulate asynchronous data loading:

// Without setTimeout - data loads synchronously (unrealistic)
window.myop_init_interface({ ... });

// With setTimeout - simulates async API call (realistic)
setTimeout(() => {
window.myop_init_interface({ ... });
});

// With delay - simulates slow network
setTimeout(() => {
window.myop_init_interface({ ... });
}, 1000); // 1 second delay

This ensures your loader state is visible and your component handles async data correctly.

Mock Data Structure​

Matching Production Data​

Your mock data should mirror the structure your host application will provide:

<script id="myop_preview">
setTimeout(() => {
window.myop_init_interface({
// Match the exact structure from your API
components: [
{
id: "comp-1",
name: "UserProfile",
developerName: "John Doe",
lastEditedDate: "2024-03-15T10:30:00.000Z",
lastVersionName: "v2.1.0",
environments: ["prod", "staging", "dev"],
tags: ["frontend", "user", "profile"]
},
{
id: "comp-2",
name: "PaymentGateway",
developerName: "Jane Smith",
lastEditedDate: "2024-03-14T09:15:00.000Z",
lastVersionName: "v1.5.2",
environments: ["prod"],
tags: ["backend", "payments", "critical"]
},
{
id: "comp-3",
name: "NotificationService",
developerName: "Bob Wilson",
lastEditedDate: "2024-03-13T14:45:00.000Z",
lastVersionName: "v3.0.0",
environments: ["staging", "dev"],
tags: ["backend", "notifications"]
}
]
});
});
</script>

Edge Cases​

Include edge cases in your mock data:

<script id="myop_preview">
setTimeout(() => {
window.myop_init_interface({
components: [
// Normal item
{
id: "1",
name: "Standard Component",
description: "A typical component"
},
// Long name
{
id: "2",
name: "This Is A Very Long Component Name That Should Be Truncated",
description: "Testing text overflow"
},
// Empty description
{
id: "3",
name: "No Description",
description: ""
},
// Special characters
{
id: "4",
name: "Test <script>alert('xss')</script>",
description: "Testing XSS prevention"
},
// Unicode characters
{
id: "5",
name: "Japanese: テスト",
description: "Testing unicode support"
}
]
});
});
</script>

Testing Different States​

Empty State​

Test how your component handles no data:

<script id="myop_preview">
setTimeout(() => {
window.myop_init_interface({
components: []
});
});
</script>

Error State​

Test error handling:

<script id="myop_preview">
setTimeout(() => {
window.myop_init_interface({
error: {
message: "Failed to fetch components",
code: "API_ERROR"
}
});
});
</script>

Loading State​

Test with a longer delay to see the loader:

<script id="myop_preview">
// Show loader for 3 seconds
setTimeout(() => {
window.myop_init_interface({
components: [/* ... */]
});
}, 3000);
</script>

Conditional Preview​

Only run mock data when not in a host application:

<script id="myop_preview">
// Only initialize if host hasn't provided data after 100ms
let dataReceived = false;

// Override to track when host provides data
const originalInit = window.myop_init_interface;
window.myop_init_interface = function(data) {
if (data) dataReceived = true;
return originalInit.apply(this, arguments);
};

// Fallback to mock data if no host
setTimeout(() => {
if (!dataReceived) {
console.log('[Myop Preview] Using mock data');
window.myop_init_interface({
components: [/* ... */]
});
}
}, 100);
</script>

Generating Mock Data​

Using Faker-style Generation​

For larger datasets, generate mock data programmatically:

<script id="myop_preview">
function generateMockData(count) {
const names = ['Auth', 'Payment', 'User', 'Dashboard', 'Report', 'Analytics'];
const types = ['Service', 'Component', 'Widget', 'Module', 'Handler'];
const developers = ['Alice', 'Bob', 'Carol', 'David', 'Eve'];
const tags = ['frontend', 'backend', 'critical', 'experimental', 'stable'];
const envs = ['prod', 'staging', 'dev'];

return Array.from({ length: count }, (_, i) => ({
id: `comp-${i + 1}`,
name: `${names[i % names.length]}${types[i % types.length]}`,
developerName: developers[i % developers.length],
lastEditedDate: new Date(Date.now() - i * 86400000).toISOString(),
lastVersionName: `v${Math.floor(i / 3) + 1}.${i % 3}.0`,
environments: envs.slice(0, (i % 3) + 1),
tags: tags.slice(0, (i % 4) + 1)
}));
}

setTimeout(() => {
window.myop_init_interface({
components: generateMockData(25)
});
});
</script>

Script ID Convention​

The id="myop_preview" convention allows:

  1. Easy identification in the DOM
  2. Host applications to remove it if needed
  3. Documentation to reference the mock data section
  4. Build tools to strip it for production
// Host application can remove preview script
document.getElementById('myop_preview')?.remove();

Best Practices​

PracticeDescription
Realistic DataUse data that matches production structure
Edge CasesInclude empty strings, long text, special characters
Multiple ItemsTest with various list sizes (0, 1, 10, 100)
Different StatesTest loading, error, and empty states
Async SimulationUse setTimeout to simulate real loading

Complete Example​

<!DOCTYPE html>
<html>
<head>
<title>My Component</title>
<style>
#loader-container { display: flex; justify-content: center; padding: 40px; }
#app-root { opacity: 0; transition: opacity 0.3s; }
.item { padding: 12px; border-bottom: 1px solid #eee; }
</style>
</head>
<body>
<div id="loader-container">Loading...</div>
<div id="app-root">
<div class="item-list"></div>
</div>

<script>
(function() {
let items = [];

function hideLoader() {
document.getElementById('loader-container').style.display = 'none';
document.getElementById('app-root').style.opacity = '1';
}

function render() {
document.querySelector('.item-list').innerHTML = items.length
? items.map(i => `<div class="item">${i.name}</div>`).join('')
: '<div class="empty">No items found</div>';
}

window.myop_init_interface = function(data) {
if (data?.items) {
items = data.items;
render();
hideLoader();
}
return { items };
};

window.myop_cta_handler = function(action, payload) {
console.log('CTA:', action, payload);
};
})();
</script>

<!-- Mock Data for Preview -->
<script id="myop_preview">
setTimeout(() => {
window.myop_init_interface({
items: [
{ id: '1', name: 'First Item' },
{ id: '2', name: 'Second Item' },
{ id: '3', name: 'Third Item' }
]
});
}, 500); // Simulate network delay
</script>
</body>
</html>

Next Steps​