Skip to content

Commit

Permalink
feat: add spawnd & expect-puppeteer
Browse files Browse the repository at this point in the history
  • Loading branch information
gregberge committed Mar 4, 2018
1 parent 19c1cbb commit 6b7f5a4
Show file tree
Hide file tree
Showing 38 changed files with 1,096 additions and 17 deletions.
8 changes: 8 additions & 0 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,17 @@ module.exports = {
},
env: {
node: true,
jest: true,
browser: true,
},
globals: {
page: true,
browser: true,
expectPage: true,
},
rules: {
'class-methods-use-this': 'off',
'no-shadow': 'off',
'no-param-reassign': 'off',
'no-use-before-define': 'off',
'import/prefer-default-export': 'off',
Expand Down
5 changes: 3 additions & 2 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
module.exports = {
globalSetup: './packages/jest-environment-puppeteer/setup',
globalTeardown: './packages/jest-environment-puppeteer/teardown',
globalSetup: './jestConfig/globalSetup',
globalTeardown: './jestConfig/globalTeardown',
testEnvironment: './packages/jest-environment-puppeteer',
setupTestFrameworkScriptFile: './packages/expect-puppeteer',
}
5 changes: 5 additions & 0 deletions jestConfig/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module.exports = {
rules: {
'import/no-extraneous-dependencies': 'off',
},
}
15 changes: 15 additions & 0 deletions jestConfig/globalSetup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const waitPort = require('wait-port')
const {
setup: setupPuppeteer,
} = require('../packages/jest-environment-puppeteer')
const spawnd = require('../packages/spawnd')

module.exports = async function setup() {
await setupPuppeteer()
global.app = spawnd('node server.js', {
cwd: __dirname,
env: process.env,
shell: true,
})
await waitPort({ port: 4444, output: 'silent' })
}
8 changes: 8 additions & 0 deletions jestConfig/globalTeardown.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const {
teardown: teardownPuppeteer,
} = require('../packages/jest-environment-puppeteer')

module.exports = async function teardown() {
await teardownPuppeteer()
if (global.app) global.app.destroy()
}
22 changes: 22 additions & 0 deletions jestConfig/public/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test App</title>
</head>
<body>
<header>This is home!</header>
<a href="/page2.html">Page 2</a>
<select name="my-select">
<option value="">Select an option</option>
<option value="opt1">Option 1</option>
<option value="opt2">Option 2</option>
</select>
<input type="file" />
<form>
<input name="firstName" />
<input name="lastName" />
</form>
<button id="dialog-btn" onclick="window.confirm('Bouh!')">Open dialog</button>
</body>
</html>
11 changes: 11 additions & 0 deletions jestConfig/public/page2.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test App</title>
</head>
<body>
<header>This is Page 2</header>
<a href="/">Home</a>
</body>
</html>
8 changes: 8 additions & 0 deletions jestConfig/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const path = require('path')
const express = require('express')

const app = express()

app.use(express.static(path.join(__dirname, 'public')))

app.listen(4444)
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
{
"private": true,
"workspaces": ["packages/*"],
"workspaces": [
"packages/*"
],
"scripts": {
"build": "lerna run build",
"ci": "yarn build && yarn lint && yarn test --ci",
Expand All @@ -18,6 +20,7 @@
"eslint-config-airbnb-base": "^12.1.0",
"eslint-config-prettier": "^2.9.0",
"eslint-plugin-import": "^2.9.0",
"express": "^4.16.2",
"jest": "^22.4.2",
"lerna": "^2.9.0",
"puppeteer": "^1.1.1",
Expand Down
2 changes: 2 additions & 0 deletions packages/expect-puppeteer/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/*
!/lib/*.js
7 changes: 7 additions & 0 deletions packages/expect-puppeteer/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Copyright 2018 Smooth Code

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
138 changes: 138 additions & 0 deletions packages/expect-puppeteer/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
# expect-puppeteer

[![Build Status][build-badge]][build]
[![version][version-badge]][package]
[![MIT License][license-badge]][license]

Assertion library for Puppeteer.

```
npm install expect-puppeteer
```

## Usage

```js
import expectPage from 'expect-puppeteer'
;(async () => {
const browser = await puppeteer.launch()
const page = await browser.newPage()
await page.goto('https://google.com')
await expectPage(page).toMatch('google')
await browser.close()
})()
```

## API

##### Table of Contents

<!-- toc -->

* [expectPage(page).toClick](#expectpagepagetoclickselectoroptions)
* [expectPage(page).toDisplayDialog](#expectpagepagetodisplaydialogblock)
* [expectPage(page).toFill](#expectpagepagetofillselectorvalueoptions)
* [expectPage(page).toFillForm](#expectpagepagetofillformselectorvaluesoptions)
* [expectPage(page).toMatch](#expectpagepagetomatchtext)
* [expectPage(page).toSelect](#expectpagepagetoselectselectorvalueortext)
* [expectPage(page).toUploadFile](#expectpagepagetouploadfileselectorfilepath)

### expectPage(page).toClick(selector[, options])

* `selector` <[string]> A [selector] to click on
* `options` <[Object]> Optional parameters
* text <[string]> A text to match

```js
await expectPage(page).toClick('button', { text: 'Home' })
```

### expectPage(page).toDisplayDialog(block)

* `block` <[function]> A [function] that should trigger a dialog

```js
await expectPage(page).toDisplayDialog(async () => {
await expectPage(page).toClick('button', { text: 'Show dialog' })
})
```

### expectPage(page).toFill(selector, value[, options])

* `selector` <[string]> A [selector] to match field
* `value` <[string]> Value to fill
* `options` <[Object]> Optional parameters
* `timeout` <[number]> maximum time to wait for in milliseconds. Defaults to `500`.

```js
await expectPage(page).toFill('input[name="firstName"]', 'James')
```

### expectPage(page).toFillForm(selector, values[, options])

* `selector` <[string]> A [selector] to match form
* `values` <[Object]> Values to fill
* `options` <[Object]> Optional parameters
* `timeout` <[number]> maximum time to wait for in milliseconds. Defaults to `500`.

```js
await expectPage(page).toFillForm('form[name="myForm"]', {
firstName: 'James',
lastName: 'Bond',
})
```

### expectPage(page).toMatch(text)

* `text` <[string]> A text to match in page
* `options` <[Object]> Optional parameters
* `timeout` <[number]> maximum time to wait for in milliseconds. Defaults to `500`.

```js
await expectPage(page).toMatch('Lorem ipsum')
```

### expectPage(page).toSelect(selector, valueOrText)

* `selector` <[string]> A [selector] to match select [element]
* `valueOrText` <[string]> Value or text matching option

```js
await expectPage(page).toSelect('select[name="choices"]', 'Choice 1')
```

### expectPage(page).toUploadFile(selector, filePath)

* `selector` <[string]> A [selector] to match input [element]
* `filePath` <[string]> A file path

```js
import path from 'path'

await expectPage(page).toUploadFile(
'input[type="file"]',
path.join(__dirname, 'file.txt'),
)
```

## License

MIT

[build-badge]: https://img.shields.io/travis/smooth-code/jest-puppeteer.svg?style=flat-square
[build]: https://travis-ci.org/smooth-code/jest-puppeteer
[version-badge]: https://img.shields.io/npm/v/expect-puppeteer.svg?style=flat-square
[package]: https://www.npmjs.com/package/expect-puppeteer
[license-badge]: https://img.shields.io/npm/l/expect-puppeteer.svg?style=flat-square
[license]: https://github.com/smooth-code/jest-puppeteer/blob/master/LICENSE
[array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array 'Array'
[boolean]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type 'Boolean'
[function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function 'Function'
[number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type 'Number'
[object]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object 'Object'
[promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise 'Promise'
[string]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type 'String'
[error]: https://nodejs.org/api/errors.html#errors_class_error 'Error'
[element]: https://developer.mozilla.org/en-US/docs/Web/API/element 'Element'
[map]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map 'Map'
[selector]: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors 'selector'
Empty file.
26 changes: 26 additions & 0 deletions packages/expect-puppeteer/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"name": "expect-puppeteer",
"description": "Assertion toolkit for Puppeteer.",
"version": "1.0.1",
"main": "lib/index.js",
"repository": "https://github.com/smooth-code/jest-puppeteer/tree/master/packages/puppeteer-expect",
"author": "Greg Bergé <berge.greg@gmail.com>",
"license": "MIT",
"keywords": [
"jest",
"puppeteer",
"jest-puppeteer",
"chromeless",
"chrome-headless",
"expect",
"assert",
"should",
"assertion"
],
"scripts": {
"prebuild": "rm -rf lib/",
"build": "babel src -d lib --ignore \"*.test.js\"",
"dev": "yarn build --watch",
"prepublishOnly": "yarn build"
}
}
60 changes: 60 additions & 0 deletions packages/expect-puppeteer/src/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/* eslint-disable no-use-before-define, no-restricted-syntax, no-await-in-loop */
import toMatch from './matchers/toMatch'
import toClick from './matchers/toClick'
import toSelect from './matchers/toSelect'
import toUploadFile from './matchers/toUploadFile'
import toFill from './matchers/toFill'
import toFillForm from './matchers/toFillForm'
import toDisplayDialog from './matchers/toDisplayDialog'
import notToMatch from './matchers/notToMatch'

const matchers = {
toMatch,
toClick,
toSelect,
toUploadFile,
toFill,
toFillForm,
toDisplayDialog,
not: {
toMatch: notToMatch,
},
}

function createMatcher(matcher, page) {
return async function throwingMatcher(...args) {
if (typeof global.expect !== 'undefined') {
global.expect.getState().assertionCalls += 1
}

try {
return await matcher(page, ...args)
} catch (error) {
Error.captureStackTrace(error, createMatcher)
throw error
}
}
}

function expectPage(page = global.page) {
const expectation = {
not: {},
}

Object.keys(matchers).forEach(key => {
if (key === 'not') return
expectation[key] = createMatcher(matchers[key], page)
})

Object.keys(matchers.not).forEach(key => {
expectation.not[key] = createMatcher(matchers.not[key], page)
})

return expectation
}

if (typeof global.expect !== 'undefined') {
global.expectPage = expectPage
}

module.exports = expectPage
12 changes: 12 additions & 0 deletions packages/expect-puppeteer/src/matchers/notToMatch.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
async function notToMatch(page, matcher, options = { timeout: 500 }) {
try {
await page.waitForFunction(
`document.body.textContent.match(new RegExp('${matcher}')) === null`,
options,
)
} catch (error) {
throw new Error(`Text found "${matcher}"`)
}
}

export default notToMatch
19 changes: 19 additions & 0 deletions packages/expect-puppeteer/src/matchers/notToMatch.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
describe('not.toMatch', () => {
beforeEach(async () => {
await page.goto('http://localhost:4444')
})

it('should be ok if text is not in the page', async () => {
await expectPage().not.toMatch('Nop!')
})

it('should return an error if text is in the page', async () => {
expect.assertions(2)

try {
await expectPage().not.toMatch('home')
} catch (error) {
expect(error.message).toMatch('Text found "home"')
}
})
})
Loading

0 comments on commit 6b7f5a4

Please sign in to comment.