JSFiddle - React, Tailwind, and code Playground
by Fagner Brack
HTML
<script src="https://code.jquery.com/qunit/qunit-2.6.1.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/qunit/qunit-2.6.1.css">
<div id="qunit"></div>
<div id="qunit-fixture"></div>
JavaScript
// ---------------------------------------------
// Ignore this, just some fake implementation
// ---------------------------------------------
const createFakeNock = () => {
const overrideFetch = (path, responseBody) => {
window.fetch = (urlToFetch) => {
const fetchResponse = {
text: () => Promise.resolve(responseBody),
json: () => Promise.resolve(JSON.parse(responseBody)),
};
if (urlToFetch !== path) {
throw new Error('Could not match request');
}
return Promise.resolve(fetchResponse);
};
};
return overrideFetch;
};
// ---------------------------------------------
// Production Code
// ---------------------------------------------
const PostsResponse_ = (htmlResponse) => {
return {
toHtmlList: () => {
const document = new DOMParser().parseFromString(htmlResponse, "text/html");
const posts = [...document.querySelectorAll('[class="post-title"]')];
const postsTitles = posts
.map((post) => post.innerHTML)
.map((title) => `<li>${title}</li>`)
.join('');
return `<ul>${postsTitles}</ul>`;
}
};
};
const createListOfPosts_ = () => {
const PostsResponse = /* import */ PostsResponse_;
return fetch('/blog/posts').then((response) => {
return response.json();
}).then((jsonResponse) => {
return PostsResponse(jsonResponse).toHtmlList();
});
};
// ---------------------------------------------
// Test Code
// ---------------------------------------------
const nock = /* import */ createFakeNock();
const createListOfPosts = /* import */ createListOfPosts_;
QUnit.test('Create a list of one post', (assert) => {
nock('/blog/posts', /*headers, parameters, etc.*/ `
<section>
<h1 class="post-title">How to bake a cake</h1>
</section>
`);
return createListOfPosts().then((list) => {
assert.strictEqual(list, '<ul><li>How to bake a cake</li></ul>');
});
});
QUnit.test('Create a list of two posts', (assert) => {
...