Skip to content

Commit

Permalink
Generate codesanbdox project from readme example
Browse files Browse the repository at this point in the history
Also simplify the main example to account for ever diminishing attention
span.
  • Loading branch information
artemave committed Dec 20, 2018
1 parent cea7cdc commit 6a3b80f
Show file tree
Hide file tree
Showing 9 changed files with 1,750 additions and 45 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
*.sw?
*.orig
/node_modules/
.DS_Store
11 changes: 11 additions & 0 deletions docs/codesandbox/basic-example/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<title>Beer App</title>
<meta charset="UTF-8" />
</head>
<body>
<div id="app"></div>
<script src="src/index.js"></script>
</body>
</html>
17 changes: 17 additions & 0 deletions docs/codesandbox/basic-example/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"name": "browser-monkey-example",
"version": "1.0.0",
"description": "Browser Monkey basic usage example",
"main": "index.html",
"scripts": {
"start": "parcel index.html --open",
"build": "parcel build index.html"
},
"dependencies": {
"browser-monkey": "latest",
"hyperdom": "latest"
},
"devDependencies": {
"parcel-bundler": "latest"
}
}
22 changes: 22 additions & 0 deletions docs/codesandbox/basic-example/src/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { html as h } from "hyperdom";

export default class App {
async getBeerInfo() {
delete this.beer;
const response = await fetch("https://api.punkapi.com/v2/beers/192");
this.beer = await response.json();
}

render() {
return h("main", [
h("h1", "Hello Lubbers"),
h("button", { onclick: () => this.getBeerInfo() }, "Beer"),
this.beer
? h("div", [
h("div", this.beer[0].name),
h("img", { src: this.beer[0].image_url, width: 100 })
])
: undefined
]);
}
}
4 changes: 4 additions & 0 deletions docs/codesandbox/basic-example/src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { append } from "hyperdom";
import App from "./app";

//append(document.querySelector("#app"), new App());
67 changes: 67 additions & 0 deletions docs/update-readme-example-links.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
const fs = require('fs')
const {escape} = require('querystring')
const {getParameters} = require('codesandbox/lib/api/define')

function generateExampleSandboxLink (exampleTemplateName, exampleCode) {
const templatePath = `${process.cwd()}/docs/codesandbox/${exampleTemplateName}`
const parameters = getParameters({
files: {
'package.json': {
content: fs.readFileSync(`${templatePath}/package.json`, {encoding: 'utf-8'})
},
'src/app.spec.js': {
content: exampleCode
},
'src/app.js': {
content: fs.readFileSync(`${templatePath}/src/app.js`, {encoding: 'utf-8'})
},
'src/index.js': {
content: fs.readFileSync(`${templatePath}/src/index.js`, {encoding: 'utf-8'})
},
'index.html': {
content: fs.readFileSync(`${templatePath}/index.html`, {encoding: 'utf-8'})
}
}
})
const url = `https://codesandbox.io/api/v1/sandboxes/define?parameters=${parameters}&query=${escape('module=/src/app.spec.js')}`
return `<a href="${url}" target="_blank" rel="noopener noreferrer">Run this example</a>`
}

const input = fs.readFileSync(`${process.cwd()}/readme.md`, {encoding: 'utf-8'})

const output = input.split('\n').reduce((result, line) => {
if (!line.match('https://codesandbox.io/api/v1/sandboxes/define')) {
result.lines.push(line)
}

if (result.currentExampleLines) {
if (line.match(/``` *$/)) {
const linkToExampleSandbox = generateExampleSandboxLink(
result.currentExampleTemplateName,
result.currentExampleLines.join('\n')
)
result.lines.push(linkToExampleSandbox)

delete result.currentExampleLines
delete result.currentExampleTemplateName
} else {
result.currentExampleLines.push(line)
}
}

const [, exampleTemplateName] = line.match(/```js +codesandbox: +([\w-]+)/) || []

if (exampleTemplateName) {
result.currentExampleTemplateName = exampleTemplateName
result.currentExampleLines = []
}

return result
}, {lines: []})

fs.promises.truncate(`${process.cwd()}/readme.md`, 0).then(() => {
return fs.writeFileSync(`${process.cwd()}/readme.md`, output.lines.join('\n'))
}).catch(e => {
console.error(e)
process.exit(1)
})
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
"description": "reliable dom testing",
"main": "index.js",
"scripts": {
"test": "standard && mocha && karma start --single-run"
"test": "standard && mocha && karma start --single-run",
"update-readme-example-links": "node ./docs/update-readme-example-links.js"
},
"author": "Tim Macfarlane <[email protected]>",
"license": "MIT",
Expand All @@ -17,6 +18,7 @@
"babel-register": "^6.24.0",
"babelify": "^7.3.0",
"browserify": "13.3.0",
"codesandbox": "^1.3.6",
"detect-node": "^2.0.3",
"express": "^4.15.2",
"httpism": "^2.6.2",
Expand Down
53 changes: 20 additions & 33 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,45 +20,32 @@ Here is an [example project](https://github.com/dereke/web-testing) that demonst

# example

```js
import createBrowser from 'browser-monkey/create';

describe('admin', function () {
let browser = createBrowser(document.body);

// describes the admin panel, with a search box, results and a user editor
let adminPanel = browser.component({
searchUsers() {
return this.find('.search');
},
userResult(name) {
// find a user in the results by their name
return this.find('.results .user', {text: name});
},
userEditor() {
// return the user editor, scoped to the .user-editor div.
return this.find('.user-editor').component({
name() { return this.find('.name'); },
email() { return this.find('.email'); },
save() { return this.find('.save'); }
});
}
```js codesandbox: basic-example
import createMonkey from "browser-monkey/create";
import createTestDiv from "browser-monkey/lib/createTestDiv";
import hyperdom from "hyperdom";
import App from "./app";

describe("beer app", () => {
let page;

beforeEach(() => {
const $testContainer = createTestDiv();
hyperdom.append($testContainer, new App());
page = createMonkey($testContainer);
});

it('can search for, edit and save a user', async () => {
await adminPanel.searchUsers().typeIn('bar');
await adminPanel.userResult('Barry').click();

let userEditor = adminPanel.userEditor();
await userEditor.name().typeIn('Barry Jones');
await userEditor.email().typeIn('[email protected]');

await userEditor.save().click();
it("greets me", async () => {
await page.find("h1").shouldHave({ text: "Hello Lubbers" });
});

// verify that the user was saved
it("shows me beer", async () => {
await page.click("Beer");
await page.shouldHave({ text: "Punk IPA" });
});
});
```
<a href="https://codesandbox.io/api/v1/sandboxes/define?parameters=N4IgZglgNgpgziAXKADgQwMYGs0HMYB0AVnAPYB2SoGFALjObUiMADrkAEHrI5aAtjB6JuIAEY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0gAURQ1gA2gRXCY9RNYCUJIniZJFi0YiJ4IWs-3WHpXEUDZEDYCIxmtr9s19QNEhDSNDYXKIfPUwT3HTbNOni1wAD8oYIW4_p6fjnT4urmNK6YNbc_98i4w4AC6BB8IIdY0-rtM8GKuA1lxcAjCIus6QbxtimkAD6aNQM-0gQG4U0iLYDgOLFMsrIbdbhyIoUNeBmxq5H360uQKdJSlTKTBUGV8gK9CMLlQb5YRbJXqVUaiKe4JVSAvZ5SGaadRXPDZlW1UnZelEQhgSSCIwBAAI5JPIagAMpjDAGC0JKCEAMRtyA5svjAb6N5-vbp1nxxQJlec5SKAA8ACEKIAPLLuaACaQXDqGMzNuwB-FVAD99k_spuK_rC0Affi0LAzYgp9B2BwUeaBDhiFIFoA-TI_4APYN_A-ghejSkqH0OQtBGw8AAKrmgAGIKAABwxSZK_GBlQP5f3IAfSBbg1Bfx_lrCYbgsEgAXs2GBWsqGIMLC0DgDsMCsIEZnW42cZIMJgbw3wZDnqkDoVQ8h996RnDOEAA&query=module%3D%2Fsrc%2Fapp.spec.js" target="_blank" rel="noopener noreferrer">Run this example</a>

# debug

Expand Down
Loading

0 comments on commit 6a3b80f

Please sign in to comment.