Skip to content

Instantly share code, notes, and snippets.

@alshdavid
Created June 29, 2020 03:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alshdavid/946b61106a9358061b43db1bce8fa734 to your computer and use it in GitHub Desktop.
Save alshdavid/946b61106a9358061b43db1bce8fa734 to your computer and use it in GitHub Desktop.
import puppeteer from 'puppeteer-core'
import express from 'express'
import * as http from 'http'
let browser: puppeteer.Browser
let app: express.Application
let server: http.Server
beforeAll(async () => {
// Open browser up using chrome installed on the machine
browser = await puppeteer.launch({
headless: false,
executablePath: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
})
// Create a webserver for the content in the dist folder
// You gotta build your web app first
app = express()
app.get('/', express.static('./dist'))
server = app.listen('8080')
})
afterAll(() => {
// When the tests are finished, close the browser and
// turn off the web server
browser.close()
server.close()
})
describe('Home Page', async () => {
// First test
test('Should send form to server', () => new Promise(async () => {
// Create a new tab on the browser and tell chrome we want
// to listen to any http calls made by the website
// Then navigate to your webserver
const page = await browser.newPage()
await page.setRequestInterception(true);
page.goto('http://localhost:8080')
// Create a listener for the first http request to the forms endpoint
const onResults = new Promise(res =>
page.on('request', async req => {
if (req.url().includes('/api/forms')) {
res(req.postData())
}
req.continue()
}
))
// Fill out the form and click submit
await page.type('#form .email', 'testman@fakeemail.com')
await page.click('#form .submit')
// Wait for the listener to resolve
const results = await onResults
// Test to see if the api call contains the right data
expect(results).toEqual({
email: 'testman@fakeemail.com'
})
}))
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment