Last active
June 29, 2020 03:21
-
-
Save alshdavid/4f9e5b1c80b1110a921692643391048f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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() | |
| }) | |
| // 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 onFormHttpCall = new Promise<any>(res => | |
| page.on('request', async req => { | |
| if (req.url().includes('/api/forms')) { | |
| const form = JSON.parse(req.postData()) | |
| res(form) | |
| } | |
| 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 onFormHttpCall | |
| // 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