Skip to content

Commit

Permalink
feat: emit beforePageLoad event (#6)
Browse files Browse the repository at this point in the history
  • Loading branch information
zeke authored Jul 25, 2020
1 parent e07508e commit 2c9fb43
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 2 deletions.
2 changes: 2 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ module.exports = function domwaiter (pages, opts = {}) {
}

async function getPage (page, emitter, opts) {
emitter.emit('beforePageLoad', page)

if (opts.json) {
try {
const json = await got(page.url).json()
Expand Down
3 changes: 2 additions & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,8 @@ This module exports a single function `domwaiter`:

The `domwaiter` function returns an event emitter which emits the following events:

- `page` - Emitted as each page has been requested and parsed. Returns an object which is a shallow clone of the original `page` object you provided, but with two added properties:
- `beforePageLoad` - Emitted with `page` object for any optional prehandling you want to do, e.g. setting up a request timer.
- `page` - Emitted after the page has been requested and the response is parsed. Returns an object which is a shallow clone of the original `page` object you provided, but with two added properties:
- `body`: the raw HTTP response body text
- `$`: The body parsed into a jQuery-like [cheerio](https://ghub.io/cheerio) DOM object.
- `error` - Emitted when an error occurs fetching a URL
Expand Down
21 changes: 20 additions & 1 deletion test.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ describe('domwaiter', () => {
expect(typeof domwaiter).toBe('function')
})

test('emits events', (done) => {
test('emits `page` and `done` events', (done) => {
const mock = nock('https://example.com')
.get('/foo')
.reply(200, '<html><title>Hello, foo</title></html>')
Expand Down Expand Up @@ -43,6 +43,25 @@ describe('domwaiter', () => {
})
})

test('emits a `beforePageLoad` event with page object', (done) => {
const mock = nock('https://example.com')
.get('/foo')
.reply(200)

const pages = [
{ url: 'https://example.com/foo' }
]

const waiter = domwaiter(pages, { minTime: 10 })

waiter
.on('beforePageLoad', (page) => {
expect(mock.isDone())
expect(page && page.url)
done()
})
})

test('emits errors for failed requests', (done) => {
const mock = nock('https://example.com')
.get('/foo')
Expand Down

0 comments on commit 2c9fb43

Please sign in to comment.