Commit 53e9983d authored by JJ Kasper's avatar JJ Kasper Committed by Joe Haddad

Add hydration callback for testing (#10195)

* Add hydration callback for testing

* Update size-limit test
parent fa65442c
...@@ -114,6 +114,14 @@ class Container extends React.Component { ...@@ -114,6 +114,14 @@ class Container extends React.Component {
} }
) )
} }
if (process.env.__NEXT_TEST_MODE) {
window.__NEXT_HYDRATED = true
if (window.__NEXT_HYDRATED_CB) {
window.__NEXT_HYDRATED_CB()
}
}
} }
componentDidUpdate() { componentDidUpdate() {
......
...@@ -8,7 +8,6 @@ import { ...@@ -8,7 +8,6 @@ import {
findPort, findPort,
killApp, killApp,
launchApp, launchApp,
waitFor,
} from 'next-test-utils' } from 'next-test-utils'
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 1 jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 1
...@@ -42,14 +41,12 @@ const runTests = () => { ...@@ -42,14 +41,12 @@ const runTests = () => {
it('should update asPath after mount', async () => { it('should update asPath after mount', async () => {
const browser = await webdriver(appPort, '/zeit/cmnt-2') const browser = await webdriver(appPort, '/zeit/cmnt-2')
await waitFor(500)
const html = await browser.eval(`document.documentElement.innerHTML`) const html = await browser.eval(`document.documentElement.innerHTML`)
expect(html).toMatch(/\/zeit\/cmnt-2/) expect(html).toMatch(/\/zeit\/cmnt-2/)
}) })
it('should not replace URL with page name while asPath is delayed', async () => { it('should not replace URL with page name while asPath is delayed', async () => {
const browser = await webdriver(appPort, '/zeit/cmnt-1') const browser = await webdriver(appPort, '/zeit/cmnt-1')
await waitFor(500)
const val = await browser.eval(`!!window.pathnames.find(function(p) { const val = await browser.eval(`!!window.pathnames.find(function(p) {
return p !== '/zeit/cmnt-1' return p !== '/zeit/cmnt-1'
})`) })`)
...@@ -84,7 +81,6 @@ describe('Auto Export', () => { ...@@ -84,7 +81,6 @@ describe('Auto Export', () => {
it('should not show hydration warning from mismatching asPath', async () => { it('should not show hydration warning from mismatching asPath', async () => {
const browser = await webdriver(appPort, '/zeit/cmnt-1') const browser = await webdriver(appPort, '/zeit/cmnt-1')
await waitFor(500)
const numCaught = await browser.eval(`window.caughtWarns.length`) const numCaught = await browser.eval(`window.caughtWarns.length`)
expect(numCaught).toBe(0) expect(numCaught).toBe(0)
......
...@@ -3,13 +3,7 @@ ...@@ -3,13 +3,7 @@
import { join } from 'path' import { join } from 'path'
import express from 'express' import express from 'express'
import http from 'http' import http from 'http'
import { import { nextBuild, nextServer, promiseCall, stopApp } from 'next-test-utils'
nextBuild,
waitFor,
nextServer,
promiseCall,
stopApp,
} from 'next-test-utils'
import { readdir, readFile, unlink, access } from 'fs-extra' import { readdir, readFile, unlink, access } from 'fs-extra'
import cheerio from 'cheerio' import cheerio from 'cheerio'
import webdriver from 'next-webdriver' import webdriver from 'next-webdriver'
...@@ -134,7 +128,6 @@ describe('Chunking', () => { ...@@ -134,7 +128,6 @@ describe('Chunking', () => {
it('should hydrate with granularChunks config', async () => { it('should hydrate with granularChunks config', async () => {
const browser = await webdriver(appPort, '/page2') const browser = await webdriver(appPort, '/page2')
await waitFor(1000)
const text = await browser.elementByCss('#padded-str').text() const text = await browser.elementByCss('#padded-str').text()
expect(text).toBe('__rad__') expect(text).toBe('__rad__')
...@@ -144,7 +137,6 @@ describe('Chunking', () => { ...@@ -144,7 +137,6 @@ describe('Chunking', () => {
it('should load chunks when navigating', async () => { it('should load chunks when navigating', async () => {
const browser = await webdriver(appPort, '/page3') const browser = await webdriver(appPort, '/page3')
await waitFor(1000)
const text = await browser const text = await browser
.elementByCss('#page2-link') .elementByCss('#page2-link')
.click() .click()
......
...@@ -8,8 +8,6 @@ export default (context, render) => { ...@@ -8,8 +8,6 @@ export default (context, render) => {
describe('Configuration', () => { describe('Configuration', () => {
it('should have config available on the client', async () => { it('should have config available on the client', async () => {
const browser = await webdriver(context.appPort, '/next-config') const browser = await webdriver(context.appPort, '/next-config')
// Wait for client side to load
await waitFor(10000)
const serverText = await browser.elementByCss('#server-only').text() const serverText = await browser.elementByCss('#server-only').text()
const serverClientText = await browser const serverClientText = await browser
......
...@@ -7,7 +7,6 @@ import { ...@@ -7,7 +7,6 @@ import {
findPort, findPort,
killApp, killApp,
renderViaHTTP, renderViaHTTP,
waitFor,
} from 'next-test-utils' } from 'next-test-utils'
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 5 jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 5
...@@ -25,7 +24,6 @@ describe('Errors on conflict between public file and page file', () => { ...@@ -25,7 +24,6 @@ describe('Errors on conflict between public file and page file', () => {
/A conflicting public file and page file was found for path/ /A conflicting public file and page file was found for path/
) )
} }
await waitFor(1000)
await killApp(app) await killApp(app)
}) })
......
...@@ -5,7 +5,6 @@ import { remove } from 'fs-extra' ...@@ -5,7 +5,6 @@ import { remove } from 'fs-extra'
import { import {
nextBuild, nextBuild,
nextStart, nextStart,
waitFor,
findPort, findPort,
killApp, killApp,
renderViaHTTP, renderViaHTTP,
...@@ -80,9 +79,6 @@ describe('CSS Module client-side navigation in Production', () => { ...@@ -80,9 +79,6 @@ describe('CSS Module client-side navigation in Production', () => {
let browser let browser
try { try {
browser = await webdriver(appPort, '/blue') browser = await webdriver(appPort, '/blue')
await waitFor(2000) // Ensure hydration
await browser.eval(`window.__did_not_ssr = 'make sure this is set'`) await browser.eval(`window.__did_not_ssr = 'make sure this is set'`)
const redColor = await browser.eval( const redColor = await browser.eval(
......
...@@ -178,7 +178,6 @@ xdescribe('Can hot reload CSS Module without losing state', () => { ...@@ -178,7 +178,6 @@ xdescribe('Can hot reload CSS Module without losing state', () => {
// FIXME: this is broken // FIXME: this is broken
it('should update CSS color without remounting <input>', async () => { it('should update CSS color without remounting <input>', async () => {
const browser = await webdriver(appPort, '/') const browser = await webdriver(appPort, '/')
await waitFor(2000) // ensure application hydrates
const desiredText = 'hello world' const desiredText = 'hello world'
await browser.elementById('text-input').type(desiredText) await browser.elementById('text-input').type(desiredText)
......
...@@ -304,7 +304,6 @@ describe('CSS Support', () => { ...@@ -304,7 +304,6 @@ describe('CSS Support', () => {
let browser let browser
try { try {
browser = await webdriver(appPort, '/page1') browser = await webdriver(appPort, '/page1')
await waitFor(2000) // ensure application hydrates
const desiredText = 'hello world' const desiredText = 'hello world'
await browser.elementById('text-input').type(desiredText) await browser.elementById('text-input').type(desiredText)
...@@ -703,7 +702,6 @@ describe('CSS Support', () => { ...@@ -703,7 +702,6 @@ describe('CSS Support', () => {
it('should have the correct color (css ordering)', async () => { it('should have the correct color (css ordering)', async () => {
const browser = await webdriver(appPort, '/') const browser = await webdriver(appPort, '/')
await waitFor(2000) // ensure application hydrates
const currentColor = await browser.eval( const currentColor = await browser.eval(
`window.getComputedStyle(document.querySelector('.my-text')).color` `window.getComputedStyle(document.querySelector('.my-text')).color`
...@@ -729,7 +727,6 @@ describe('CSS Support', () => { ...@@ -729,7 +727,6 @@ describe('CSS Support', () => {
it('should have the correct color (css ordering)', async () => { it('should have the correct color (css ordering)', async () => {
const browser = await webdriver(appPort, '/') const browser = await webdriver(appPort, '/')
await waitFor(2000) // ensure application hydrates
const currentColor = await browser.eval( const currentColor = await browser.eval(
`window.getComputedStyle(document.querySelector('.my-text')).color` `window.getComputedStyle(document.querySelector('.my-text')).color`
......
...@@ -8,7 +8,6 @@ import { ...@@ -8,7 +8,6 @@ import {
launchApp, launchApp,
renderViaHTTP, renderViaHTTP,
killApp, killApp,
waitFor,
} from 'next-test-utils' } from 'next-test-utils'
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 1 jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 1
...@@ -34,7 +33,6 @@ describe('Handles Duplicate Pages', () => { ...@@ -34,7 +33,6 @@ describe('Handles Duplicate Pages', () => {
onStderr: handleOutput, onStderr: handleOutput,
}) })
await renderViaHTTP(appPort, '/hello') await renderViaHTTP(appPort, '/hello')
await waitFor(3000)
await killApp(app) await killApp(app)
expect(output).toMatch(/Duplicate page detected/) expect(output).toMatch(/Duplicate page detected/)
}) })
......
...@@ -304,7 +304,6 @@ function runTests(dev) { ...@@ -304,7 +304,6 @@ function runTests(dev) {
expect(html).toMatch(/onmpost:.*pending/) expect(html).toMatch(/onmpost:.*pending/)
const browser = await webdriver(appPort, '/on-mount/post-1') const browser = await webdriver(appPort, '/on-mount/post-1')
await waitFor(1000)
const text = await browser.eval(`document.body.innerHTML`) const text = await browser.eval(`document.body.innerHTML`)
expect(text).toMatch(/onmpost:.*post-1/) expect(text).toMatch(/onmpost:.*post-1/)
}) })
...@@ -316,14 +315,12 @@ function runTests(dev) { ...@@ -316,14 +315,12 @@ function runTests(dev) {
it('should update with a hash in the URL', async () => { it('should update with a hash in the URL', async () => {
const browser = await webdriver(appPort, '/on-mount/post-1#abc') const browser = await webdriver(appPort, '/on-mount/post-1#abc')
await waitFor(1000)
const text = await browser.eval(`document.body.innerHTML`) const text = await browser.eval(`document.body.innerHTML`)
expect(text).toMatch(/onmpost:.*post-1/) expect(text).toMatch(/onmpost:.*post-1/)
}) })
it('should scroll to a hash on mount', async () => { it('should scroll to a hash on mount', async () => {
const browser = await webdriver(appPort, '/on-mount/post-1#item-400') const browser = await webdriver(appPort, '/on-mount/post-1#item-400')
await waitFor(1000)
const text = await browser.eval(`document.body.innerHTML`) const text = await browser.eval(`document.body.innerHTML`)
expect(text).toMatch(/onmpost:.*post-1/) expect(text).toMatch(/onmpost:.*post-1/)
...@@ -334,7 +331,6 @@ function runTests(dev) { ...@@ -334,7 +331,6 @@ function runTests(dev) {
it('should scroll to a hash on client-side navigation', async () => { it('should scroll to a hash on client-side navigation', async () => {
const browser = await webdriver(appPort, '/') const browser = await webdriver(appPort, '/')
await waitFor(1000)
await browser.elementByCss('#view-dynamic-with-hash').click() await browser.elementByCss('#view-dynamic-with-hash').click()
await browser.waitForElementByCss('p') await browser.waitForElementByCss('p')
......
...@@ -49,7 +49,6 @@ describe('Empty Project', () => { ...@@ -49,7 +49,6 @@ describe('Empty Project', () => {
it('should show empty object warning during client transition', async () => { it('should show empty object warning during client transition', async () => {
const browser = await webdriver(appPort, '/static') const browser = await webdriver(appPort, '/static')
await waitFor(1000)
await browser.eval(`(function() { await browser.eval(`(function() {
window.gotWarn = false window.gotWarn = false
const origWarn = console.warn const origWarn = console.warn
......
...@@ -9,7 +9,6 @@ import { ...@@ -9,7 +9,6 @@ import {
startCleanStaticServer, startCleanStaticServer,
stopApp, stopApp,
renderViaHTTP, renderViaHTTP,
waitFor,
} from 'next-test-utils' } from 'next-test-utils'
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60
...@@ -41,7 +40,6 @@ describe('Export Dyanmic Pages', () => { ...@@ -41,7 +40,6 @@ describe('Export Dyanmic Pages', () => {
expect.assertions(1) expect.assertions(1)
const browser = await webdriver(port, '/regression/jeff-is-cool') const browser = await webdriver(port, '/regression/jeff-is-cool')
try { try {
await waitFor(3000)
expect(await browser.eval(`window.__AS_PATHS`)).toEqual([ expect(await browser.eval(`window.__AS_PATHS`)).toEqual([
'/regression/jeff-is-cool', '/regression/jeff-is-cool',
]) ])
......
...@@ -9,7 +9,6 @@ import { ...@@ -9,7 +9,6 @@ import {
startCleanStaticServer, startCleanStaticServer,
stopApp, stopApp,
renderViaHTTP, renderViaHTTP,
waitFor,
} from 'next-test-utils' } from 'next-test-utils'
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60
...@@ -41,7 +40,6 @@ describe('Export Dyanmic Pages', () => { ...@@ -41,7 +40,6 @@ describe('Export Dyanmic Pages', () => {
expect.assertions(1) expect.assertions(1)
const browser = await webdriver(port, '/regression/jeff-is-cool') const browser = await webdriver(port, '/regression/jeff-is-cool')
try { try {
await waitFor(3000)
expect(await browser.eval(`window.__AS_PATHS`)).toEqual([ expect(await browser.eval(`window.__AS_PATHS`)).toEqual([
'/regression/jeff-is-cool', '/regression/jeff-is-cool',
]) ])
......
/* eslint-env jest */ /* eslint-env jest */
import webdriver from 'next-webdriver' import webdriver from 'next-webdriver'
import { check, waitFor, getBrowserBodyText } from 'next-test-utils' import { check, getBrowserBodyText } from 'next-test-utils'
export default function(context) { export default function(context) {
describe('Render via browser', () => { describe('Render via browser', () => {
...@@ -184,7 +184,6 @@ export default function(context) { ...@@ -184,7 +184,6 @@ export default function(context) {
it('should update query after mount', async () => { it('should update query after mount', async () => {
const browser = await webdriver(context.port, '/query-update?hello=world') const browser = await webdriver(context.port, '/query-update?hello=world')
await waitFor(2000)
const query = await browser.elementByCss('#query').text() const query = await browser.elementByCss('#query').text()
expect(JSON.parse(query)).toEqual({ hello: 'world', a: 'blue' }) expect(JSON.parse(query)).toEqual({ hello: 'world', a: 'blue' })
await browser.close() await browser.close()
......
/* eslint-env jest */ /* eslint-env jest */
import webdriver from 'next-webdriver' import webdriver from 'next-webdriver'
import { check, waitFor, getBrowserBodyText } from 'next-test-utils' import { check, getBrowserBodyText } from 'next-test-utils'
export default function(context) { export default function(context) {
describe('Render via browser', () => { describe('Render via browser', () => {
...@@ -191,7 +191,6 @@ export default function(context) { ...@@ -191,7 +191,6 @@ export default function(context) {
it('should update query after mount', async () => { it('should update query after mount', async () => {
const browser = await webdriver(context.port, '/query-update?hello=world') const browser = await webdriver(context.port, '/query-update?hello=world')
await waitFor(2000)
const query = await browser.elementByCss('#query').text() const query = await browser.elementByCss('#query').text()
expect(JSON.parse(query)).toEqual({ hello: 'world', a: 'blue' }) expect(JSON.parse(query)).toEqual({ hello: 'world', a: 'blue' })
await browser.close() await browser.close()
......
...@@ -8,7 +8,6 @@ import { ...@@ -8,7 +8,6 @@ import {
startApp, startApp,
stopApp, stopApp,
renderViaHTTP, renderViaHTTP,
waitFor,
} from 'next-test-utils' } from 'next-test-utils'
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 5 jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 5
...@@ -34,7 +33,6 @@ describe('future.excludeDefaultMomentLocales', () => { ...@@ -34,7 +33,6 @@ describe('future.excludeDefaultMomentLocales', () => {
it('should load momentjs', async () => { it('should load momentjs', async () => {
const browser = await webdriver(appPort, '/') const browser = await webdriver(appPort, '/')
await waitFor(5000)
expect(await browser.elementByCss('h1').text()).toMatch(/current time/i) expect(await browser.elementByCss('h1').text()).toMatch(/current time/i)
const locales = await browser.eval('moment.locales()') const locales = await browser.eval('moment.locales()')
expect(locales).toEqual(['en']) expect(locales).toEqual(['en'])
......
...@@ -3,13 +3,7 @@ ...@@ -3,13 +3,7 @@
import path from 'path' import path from 'path'
import fs from 'fs-extra' import fs from 'fs-extra'
import webdriver from 'next-webdriver' import webdriver from 'next-webdriver'
import { import { nextBuild, nextStart, findPort, killApp } from 'next-test-utils'
nextBuild,
nextStart,
findPort,
waitFor,
killApp,
} from 'next-test-utils'
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 1 jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 1
const appDir = path.join(__dirname, '..') const appDir = path.join(__dirname, '..')
...@@ -27,7 +21,6 @@ describe('Hydration', () => { ...@@ -27,7 +21,6 @@ describe('Hydration', () => {
it('Hydrates correctly', async () => { it('Hydrates correctly', async () => {
const browser = await webdriver(appPort, '/') const browser = await webdriver(appPort, '/')
await waitFor(2000)
expect(await browser.eval('window.didHydrate')).toBe(true) expect(await browser.eval('window.didHydrate')).toBe(true)
}) })
}) })
...@@ -7,7 +7,6 @@ import { ...@@ -7,7 +7,6 @@ import {
nextStart, nextStart,
launchApp, launchApp,
findPort, findPort,
waitFor,
killApp, killApp,
} from 'next-test-utils' } from 'next-test-utils'
...@@ -19,12 +18,11 @@ let appPort ...@@ -19,12 +18,11 @@ let appPort
const runTest = () => { const runTest = () => {
it('Has correct initial ref values', async () => { it('Has correct initial ref values', async () => {
const browser = await webdriver(appPort, '/') const browser = await webdriver(appPort, '/')
await waitFor(2000)
expect(await browser.elementByCss('#ref-val').text()).toContain('76px') expect(await browser.elementByCss('#ref-val').text()).toContain('76px')
}) })
} }
describe('Hydration', () => { describe('Initial Refs', () => {
describe('production mode', () => { describe('production mode', () => {
beforeAll(async () => { beforeAll(async () => {
await nextBuild(appDir) await nextBuild(appDir)
......
...@@ -64,7 +64,6 @@ const showsError = async ( ...@@ -64,7 +64,6 @@ const showsError = async (
const noError = async (pathname, click = false) => { const noError = async (pathname, click = false) => {
const browser = await webdriver(appPort, '/') const browser = await webdriver(appPort, '/')
await waitFor(2000)
await browser.eval(`(function() { await browser.eval(`(function() {
window.caughtErrors = [] window.caughtErrors = []
window.addEventListener('error', function (error) { window.addEventListener('error', function (error) {
......
...@@ -35,7 +35,6 @@ const noError = async pathname => { ...@@ -35,7 +35,6 @@ const noError = async pathname => {
const didPrefetch = async pathname => { const didPrefetch = async pathname => {
const browser = await webdriver(appPort, pathname) const browser = await webdriver(appPort, pathname)
await waitFor(500)
const links = await browser.elementsByCss('link[rel=prefetch]') const links = await browser.elementsByCss('link[rel=prefetch]')
let found = false let found = false
......
...@@ -7,7 +7,6 @@ import { ...@@ -7,7 +7,6 @@ import {
findPort, findPort,
launchApp, launchApp,
killApp, killApp,
waitFor,
runNextCommand, runNextCommand,
nextServer, nextServer,
startApp, startApp,
...@@ -29,7 +28,6 @@ function runTests() { ...@@ -29,7 +28,6 @@ function runTests() {
it('should render dynamic server rendered values on client mount', async () => { it('should render dynamic server rendered values on client mount', async () => {
const browser = await webdriver(appPort, '/') const browser = await webdriver(appPort, '/')
await waitFor(5000)
const text = await browser.elementByCss('#first-render').text() const text = await browser.elementByCss('#first-render').text()
// Failure case is 'Index<!-- -->3<!-- --><!-- -->' // Failure case is 'Index<!-- -->3<!-- --><!-- -->'
......
...@@ -8,7 +8,6 @@ import { ...@@ -8,7 +8,6 @@ import {
findPort, findPort,
launchApp, launchApp,
killApp, killApp,
waitFor,
nextBuild, nextBuild,
nextStart, nextStart,
renderViaHTTP, renderViaHTTP,
...@@ -57,7 +56,6 @@ function runTests() { ...@@ -57,7 +56,6 @@ function runTests() {
it('should call clientInit from plugin correctly', async () => { it('should call clientInit from plugin correctly', async () => {
const browser = await webdriver(appPort, '/') const browser = await webdriver(appPort, '/')
await waitFor(250)
expect(await browser.eval('window.didClientInit')).toBe(true) expect(await browser.eval('window.didClientInit')).toBe(true)
}) })
...@@ -125,7 +123,6 @@ describe('Next.js plugins', () => { ...@@ -125,7 +123,6 @@ describe('Next.js plugins', () => {
it('should expose a plugins config', async () => { it('should expose a plugins config', async () => {
const browser = await webdriver(appPort, '/') const browser = await webdriver(appPort, '/')
await waitFor(500)
expect(await browser.eval('window.initClientConfig')).toBe('world') expect(await browser.eval('window.initClientConfig')).toBe('world')
}) })
}) })
......
/* eslint-env jest */ /* eslint-env jest */
/* global jasmine */ /* global jasmine */
import { join } from 'path' import { join } from 'path'
import { import { nextBuild, findPort, nextStart, killApp } from 'next-test-utils'
nextBuild,
findPort,
waitFor,
nextStart,
killApp,
} from 'next-test-utils'
import webdriver from 'next-webdriver' import webdriver from 'next-webdriver'
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 1 jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 1
...@@ -34,7 +28,6 @@ describe('Polyfills', () => { ...@@ -34,7 +28,6 @@ describe('Polyfills', () => {
it('should alias fetch', async () => { it('should alias fetch', async () => {
const browser = await webdriver(appPort, '/fetch') const browser = await webdriver(appPort, '/fetch')
await waitFor(1000)
const text = await browser.elementByCss('#test-status').text() const text = await browser.elementByCss('#test-status').text()
expect(text).toBe('pass') expect(text).toBe('pass')
......
...@@ -36,7 +36,6 @@ describe('Prefetching Links in viewport', () => { ...@@ -36,7 +36,6 @@ describe('Prefetching Links in viewport', () => {
let browser let browser
try { try {
browser = await webdriver(appPort, '/') browser = await webdriver(appPort, '/')
await waitFor(2 * 1000)
const links = await browser.elementsByCss('link[rel=prefetch]') const links = await browser.elementsByCss('link[rel=prefetch]')
let found = false let found = false
...@@ -124,7 +123,6 @@ describe('Prefetching Links in viewport', () => { ...@@ -124,7 +123,6 @@ describe('Prefetching Links in viewport', () => {
it('should not prefetch when prefetch is explicitly set to false', async () => { it('should not prefetch when prefetch is explicitly set to false', async () => {
const browser = await webdriver(appPort, '/opt-out') const browser = await webdriver(appPort, '/opt-out')
await waitFor(2 * 1000)
const links = await browser.elementsByCss('link[rel=prefetch]') const links = await browser.elementsByCss('link[rel=prefetch]')
let found = false let found = false
...@@ -141,7 +139,6 @@ describe('Prefetching Links in viewport', () => { ...@@ -141,7 +139,6 @@ describe('Prefetching Links in viewport', () => {
it('should not duplicate prefetches', async () => { it('should not duplicate prefetches', async () => {
const browser = await webdriver(appPort, '/multi-prefetch') const browser = await webdriver(appPort, '/multi-prefetch')
await waitFor(2 * 1000)
const links = await browser.elementsByCss('link[rel=prefetch]') const links = await browser.elementsByCss('link[rel=prefetch]')
...@@ -163,7 +160,6 @@ describe('Prefetching Links in viewport', () => { ...@@ -163,7 +160,6 @@ describe('Prefetching Links in viewport', () => {
// info: both `/` and `/de-duped` ref the `/first` page, which we don't // info: both `/` and `/de-duped` ref the `/first` page, which we don't
// want to be re-fetched/re-observed. // want to be re-fetched/re-observed.
const browser = await webdriver(appPort, '/') const browser = await webdriver(appPort, '/')
await waitFor(2 * 1000)
await browser.eval(`(function() { await browser.eval(`(function() {
window.calledPrefetch = false window.calledPrefetch = false
window.next.router.prefetch = function() { window.next.router.prefetch = function() {
......
...@@ -150,9 +150,6 @@ const navigateTest = (dev = false) => { ...@@ -150,9 +150,6 @@ const navigateTest = (dev = false) => {
let text = await browser.elementByCss('p').text() let text = await browser.elementByCss('p').text()
expect(text).toMatch(/hello.*?world/) expect(text).toMatch(/hello.*?world/)
// hydration
await waitFor(2500)
// go to /another // go to /another
async function goFromHomeToAnother() { async function goFromHomeToAnother() {
await browser.eval('window.beforeAnother = true') await browser.eval('window.beforeAnother = true')
...@@ -322,7 +319,6 @@ const runTests = (dev = false) => { ...@@ -322,7 +319,6 @@ const runTests = (dev = false) => {
it('should parse query values on mount correctly', async () => { it('should parse query values on mount correctly', async () => {
const browser = await webdriver(appPort, '/blog/post-1?another=value') const browser = await webdriver(appPort, '/blog/post-1?another=value')
await waitFor(2000)
const text = await browser.elementByCss('#query').text() const text = await browser.elementByCss('#query').text()
expect(text).toMatch(/another.*?value/) expect(text).toMatch(/another.*?value/)
expect(text).toMatch(/post.*?post-1/) expect(text).toMatch(/post.*?post-1/)
...@@ -330,7 +326,6 @@ const runTests = (dev = false) => { ...@@ -330,7 +326,6 @@ const runTests = (dev = false) => {
it('should reload page on failed data request', async () => { it('should reload page on failed data request', async () => {
const browser = await webdriver(appPort, '/') const browser = await webdriver(appPort, '/')
await waitFor(500)
await browser.eval('window.beforeClick = true') await browser.eval('window.beforeClick = true')
await browser.elementByCss('#broken-post').click() await browser.elementByCss('#broken-post').click()
await waitFor(1000) await waitFor(1000)
......
...@@ -608,7 +608,6 @@ describe('Production Usage', () => { ...@@ -608,7 +608,6 @@ describe('Production Usage', () => {
it('should handle AMP correctly in IE', async () => { it('should handle AMP correctly in IE', async () => {
const browser = await webdriver(appPort, '/some-amp') const browser = await webdriver(appPort, '/some-amp')
await waitFor(1000)
const text = await browser.elementByCss('p').text() const text = await browser.elementByCss('p').text()
expect(text).toBe('Not AMP') expect(text).toBe('Not AMP')
}) })
......
...@@ -6,10 +6,10 @@ import { renderViaHTTP, getBrowserBodyText, waitFor } from 'next-test-utils' ...@@ -6,10 +6,10 @@ import { renderViaHTTP, getBrowserBodyText, waitFor } from 'next-test-utils'
import { recursiveReadDir } from 'next/dist/lib/recursive-readdir' import { recursiveReadDir } from 'next/dist/lib/recursive-readdir'
import { homedir } from 'os' import { homedir } from 'os'
// Does the same evaluation checking for INJECTED for 15 seconds, triggering every 500ms // Does the same evaluation checking for INJECTED for 5 seconds after hydration, triggering every 500ms
async function checkInjected(browser) { async function checkInjected(browser) {
const start = Date.now() const start = Date.now()
while (Date.now() - start < 15000) { while (Date.now() - start < 5000) {
const bodyText = await getBrowserBodyText(browser) const bodyText = await getBrowserBodyText(browser)
if (/INJECTED/.test(bodyText)) { if (/INJECTED/.test(bodyText)) {
throw new Error('Vulnerable to XSS attacks') throw new Error('Vulnerable to XSS attacks')
......
...@@ -81,7 +81,7 @@ describe('Production response size', () => { ...@@ -81,7 +81,7 @@ describe('Production response size', () => {
) )
// These numbers are without gzip compression! // These numbers are without gzip compression!
const delta = responseSizeKilobytes - 234 const delta = responseSizeKilobytes - 235
expect(delta).toBeLessThanOrEqual(0) // don't increase size expect(delta).toBeLessThanOrEqual(0) // don't increase size
expect(delta).toBeGreaterThanOrEqual(-1) // don't decrease size without updating target expect(delta).toBeGreaterThanOrEqual(-1) // don't decrease size without updating target
}) })
......
...@@ -82,7 +82,12 @@ export function runNextCommand(argv, options = {}) { ...@@ -82,7 +82,12 @@ export function runNextCommand(argv, options = {}) {
const nextBin = path.join(nextDir, 'dist/bin/next') const nextBin = path.join(nextDir, 'dist/bin/next')
const cwd = options.cwd || nextDir const cwd = options.cwd || nextDir
// Let Next.js decide the environment // Let Next.js decide the environment
const env = { ...process.env, ...options.env, NODE_ENV: '' } const env = {
...process.env,
...options.env,
NODE_ENV: '',
__NEXT_TEST_MODE: 'true',
}
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
console.log(`Running command "next ${argv.join(' ')}"`) console.log(`Running command "next ${argv.join(' ')}"`)
......
interface Chain {
elementByCss: () => Chain
elementById: () => Chain
getValue: () => Chain
text: () => Chain
type: () => Chain
moveTo: () => Chain
getComputedCss: () => Chain
getAttribute: () => Chain
hasElementByCssSelector: () => Chain
click: () => Chain
elementsByCss: () => Chain
waitForElementByCss: () => Chain
eval: () => Chain
log: () => Chain
url: () => Chain
back: () => Chain
forward: () => Chain
refresh: () => Chain
close: () => Chain
quit: () => Chain
}
export default function(
appPort: number,
path: string,
waitHydration?: boolean
): Promise<Chain>
/// <reference types="./next-webdriver" />
import os from 'os' import os from 'os'
import path from 'path' import path from 'path'
import fetch from 'node-fetch' import fetch from 'node-fetch'
import { until, Builder, By } from 'selenium-webdriver' import Chain from './wd-chain'
import { Builder, By } from 'selenium-webdriver'
import { Options as ChromeOptions } from 'selenium-webdriver/chrome' import { Options as ChromeOptions } from 'selenium-webdriver/chrome'
import { Options as SafariOptions } from 'selenium-webdriver/safari' import { Options as SafariOptions } from 'selenium-webdriver/safari'
import { Options as FireFoxOptions } from 'selenium-webdriver/firefox' import { Options as FireFoxOptions } from 'selenium-webdriver/firefox'
...@@ -153,7 +155,7 @@ const freshWindow = async () => { ...@@ -153,7 +155,7 @@ const freshWindow = async () => {
await browser.switchTo().window(newWindow) await browser.switchTo().window(newWindow)
} }
export default async (appPort, path) => { export default async (appPort, path, waitHydration = true) => {
if (!initialWindow) { if (!initialWindow) {
initialWindow = await browser.getWindowHandle() initialWindow = await browser.getWindowHandle()
} }
...@@ -173,137 +175,33 @@ export default async (appPort, path) => { ...@@ -173,137 +175,33 @@ export default async (appPort, path) => {
await browser.get(url) await browser.get(url)
console.log(`\n> Loaded browser with ${url}\n`) console.log(`\n> Loaded browser with ${url}\n`)
class Chain { // Wait for application to hydrate
updateChain(nextCall) { if (waitHydration) {
if (!this.promise) { console.log(`\n> Waiting hydration for ${url}\n`)
this.promise = Promise.resolve() await browser.executeAsyncScript(function() {
} var callback = arguments[arguments.length - 1]
this.promise = this.promise.then(nextCall)
this.then = cb => this.promise.then(cb)
this.catch = cb => this.promise.catch(cb)
this.finally = cb => this.promise.finally(cb)
return this
}
elementByCss(sel) {
return this.updateChain(() =>
browser.findElement(By.css(sel)).then(el => {
el.sel = sel
el.text = () => el.getText()
el.getComputedCss = prop => el.getCssValue(prop)
el.type = text => el.sendKeys(text)
el.getValue = () =>
browser.executeScript(
`return document.querySelector('${sel}').value`
)
return el
})
)
}
elementById(sel) {
return this.elementByCss(`#${sel}`)
}
getValue() {
return this.updateChain(el =>
browser.executeScript(
`return document.querySelector('${el.sel}').value`
)
)
}
text() {
return this.updateChain(el => el.getText())
}
type(text) {
return this.updateChain(el => el.sendKeys(text))
}
moveTo() {
return this.updateChain(el => {
return browser
.actions()
.move({ origin: el })
.perform()
.then(() => el)
})
}
getComputedCss(prop) { // if it's not a Next.js app return
return this.updateChain(el => { if (document.documentElement.innerHTML.indexOf('__NEXT_DATA__') === -1) {
return el.getCssValue(prop) callback()
})
} }
getAttribute(attr) { if (window.__NEXT_HYDRATED) {
return this.updateChain(el => el.getAttribute(attr)) callback()
} else {
var timeout = setTimeout(callback, 10 * 1000)
window.__NEXT_HYDRATED_CB = function() {
clearTimeout(timeout)
callback()
} }
hasElementByCssSelector(sel) {
return this.eval(`document.querySelector('${sel}')`)
} }
click() {
return this.updateChain(el => {
return el.click().then(() => el)
}) })
} console.log(`\n> Hydration complete for ${url}\n`)
elementsByCss(sel) {
return this.updateChain(() => browser.findElements(By.css(sel)))
}
waitForElementByCss(sel, timeout) {
return this.updateChain(() =>
browser.wait(until.elementLocated(By.css(sel), timeout))
)
}
eval(snippet) {
if (typeof snippet === 'string' && !snippet.startsWith('return')) {
snippet = `return ${snippet}`
}
return this.updateChain(() => browser.executeScript(snippet))
}
log(type) {
return this.updateChain(() =>
browser
.manage()
.logs()
.get(type)
)
}
url() {
return this.updateChain(() => browser.getCurrentUrl())
}
back() {
return this.updateChain(() => browser.navigate().back())
}
forward() {
return this.updateChain(() => browser.navigate().forward())
}
refresh() {
return this.updateChain(() => browser.navigate().refresh())
}
close() {
return this.updateChain(() => Promise.resolve())
}
quit() {
return this.close()
}
} }
const promiseProp = new Set(['then', 'catch', 'finally']) const promiseProp = new Set(['then', 'catch', 'finally'])
return new Proxy(new Chain(), { return new Proxy(new Chain(browser), {
get(obj, prop) { get(obj, prop) {
if (obj[prop] || promiseProp.has(prop)) { if (obj[prop] || promiseProp.has(prop)) {
return obj[prop] return obj[prop]
......
import { until, By } from 'selenium-webdriver'
export default class Chain {
constructor(browser) {
this.browser = browser
}
updateChain(nextCall) {
if (!this.promise) {
this.promise = Promise.resolve()
}
this.promise = this.promise.then(nextCall)
this.then = cb => this.promise.then(cb)
this.catch = cb => this.promise.catch(cb)
this.finally = cb => this.promise.finally(cb)
return this
}
elementByCss(sel) {
return this.updateChain(() =>
this.browser.findElement(By.css(sel)).then(el => {
el.sel = sel
el.text = () => el.getText()
el.getComputedCss = prop => el.getCssValue(prop)
el.type = text => el.sendKeys(text)
el.getValue = () =>
this.browser.executeScript(
`return document.querySelector('${sel}').value`
)
return el
})
)
}
elementById(sel) {
return this.elementByCss(`#${sel}`)
}
getValue() {
return this.updateChain(el =>
this.browser.executeScript(
`return document.querySelector('${el.sel}').value`
)
)
}
text() {
return this.updateChain(el => el.getText())
}
type(text) {
return this.updateChain(el => el.sendKeys(text))
}
moveTo() {
return this.updateChain(el => {
return this.browser
.actions()
.move({ origin: el })
.perform()
.then(() => el)
})
}
getComputedCss(prop) {
return this.updateChain(el => {
return el.getCssValue(prop)
})
}
getAttribute(attr) {
return this.updateChain(el => el.getAttribute(attr))
}
hasElementByCssSelector(sel) {
return this.eval(`document.querySelector('${sel}')`)
}
click() {
return this.updateChain(el => {
return el.click().then(() => el)
})
}
elementsByCss(sel) {
return this.updateChain(() => this.browser.findElements(By.css(sel)))
}
waitForElementByCss(sel, timeout) {
return this.updateChain(() =>
this.browser.wait(until.elementLocated(By.css(sel), timeout))
)
}
eval(snippet) {
if (typeof snippet === 'string' && !snippet.startsWith('return')) {
snippet = `return ${snippet}`
}
return this.updateChain(() => this.browser.executeScript(snippet))
}
log(type) {
return this.updateChain(() =>
this.browser
.manage()
.logs()
.get(type)
)
}
url() {
return this.updateChain(() => this.browser.getCurrentUrl())
}
back() {
return this.updateChain(() => this.browser.navigate().back())
}
forward() {
return this.updateChain(() => this.browser.navigate().forward())
}
refresh() {
return this.updateChain(() => this.browser.navigate().refresh())
}
close() {
return this.updateChain(() => Promise.resolve())
}
quit() {
return this.close()
}
}
{
"compilerOptions": {
"module": "esnext",
"target": "es6",
"allowJs": true,
"baseUrl": "./lib"
},
"include": ["./**/*"]
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment