Commit 1dc52dbc authored by Arunoda Susiripala's avatar Arunoda Susiripala Committed by Naoyuki Kanezawa

New test setup (#640)

* Use jest-cli instead of gulp plugin.

* Use jest-cli instead of gulp plugin.

* Move fixtures into the examples dir.

* Move test code of example app to the basic example.

* Add isolated tests for server/resolve

* Allow tests to use cheerio.

* Use portfinder to get a unique port.

* Move back integration tests into the example dir.

* Introduce next-test-utils.

* Remove gulp-jest

* Add coveralls support.

* Use transpiled version of code in dist.
This is to make sure same file gets covered
by both unit/isolated tests and integration tests.

* Add support for source maps.

* Use code from dist always.

* Use nyc to stop instrument.

* Add integration test suite for production usage.

* Use jest-cli.

* Add support for running e2e tests.

* Check gzipPath with fs.stat before serving
Otherwise, serve package might throw issues other than ENOENT

* Install chromedriver with npm install.

* Install chrome on travis-ci.

* Add --forceExit to Jest.

* Run tests only on Node v6.
That's because selenium-webdriver only supports
Node 6 LTS.

* Use chromedriver NPM module to install chromedriver.

* Use wd as the webdriver client.

* Run chromedriver before tests.

* Run travis for both node 4 and 6

* Remove unwanted npm install script.

* Move some common text utilities to next-test-utils

* Add lint checks and testing in npm prepublish hook.

* Use npm on travis-ci.
We are having some caching issues with yarn and chromedriver.

* Make tests work on windows.\n But chromedriver doesn't work.

* Clean up dependencies.

* Run chromedriver in background without any tools.

* Fix a typo in the code.

* Use ES6 features used in node4 inside the gulpfile.

* Add some comments.

* Add support for running in windows.

* Stop chromedriver properly on windows.

* Fix typos.
parent 4c32dd96
...@@ -5,5 +5,10 @@ ...@@ -5,5 +5,10 @@
"transform-object-rest-spread", "transform-object-rest-spread",
"transform-class-properties", "transform-class-properties",
"transform-runtime" "transform-runtime"
] ],
"env": {
"test": {
"plugins": ["istanbul"]
}
}
} }
sudo: required
dist: trusty
addons:
apt:
sources:
- google-chrome
packages:
- google-chrome-stable
language: node_js language: node_js
node_js: node_js:
- "node"
- "6"
- "4" - "4"
- "6"
cache: cache:
yarn: true
directories: directories:
- node_modules - node_modules
install: before_install:
- curl -o- -L https://yarnpkg.com/install.sh | bash - rm yarn.lock
- export PATH=$HOME/.yarn/bin:$PATH - export DISPLAY=:99.0
- yarn --ignore-engines - sh -e /etc/init.d/xvfb start
- sleep 3
script:
- echo "No need to use npm test since it's done in the install section via 'npm prepublish'"
after_script: npm run coveralls after_script: npm run coveralls
...@@ -8,8 +8,9 @@ const sequence = require('run-sequence') ...@@ -8,8 +8,9 @@ const sequence = require('run-sequence')
const webpack = require('webpack') const webpack = require('webpack')
const webpackStream = require('webpack-stream') const webpackStream = require('webpack-stream')
const del = require('del') const del = require('del')
const jest = require('gulp-jest') const childProcess = require('child_process')
const isWindows = /^win/.test(process.platform)
const babelOptions = JSON.parse(fs.readFileSync('.babelrc', 'utf-8')) const babelOptions = JSON.parse(fs.readFileSync('.babelrc', 'utf-8'))
gulp.task('compile', [ gulp.task('compile', [
...@@ -123,21 +124,6 @@ gulp.task('build-prefetcher', ['compile-lib', 'compile-client'], () => { ...@@ -123,21 +124,6 @@ gulp.task('build-prefetcher', ['compile-lib', 'compile-client'], () => {
.pipe(notify('Built release prefetcher')) .pipe(notify('Built release prefetcher'))
}) })
gulp.task('test', ['compile'], () => {
return gulp.src('./test')
.pipe(jest.default({
coverage: true,
verbose: true,
config: {
rootDir: './test',
testEnvironment: 'node',
coveragePathIgnorePatterns: [
'test/.*'
]
}
}))
})
gulp.task('bench', ['compile', 'copy', 'compile-bench', 'copy-bench-fixtures'], () => { gulp.task('bench', ['compile', 'copy', 'compile-bench', 'copy-bench-fixtures'], () => {
return gulp.src('dist/bench/*.js', {read: false}) return gulp.src('dist/bench/*.js', {read: false})
.pipe(benchmark({ .pipe(benchmark({
...@@ -193,7 +179,6 @@ gulp.task('default', [ ...@@ -193,7 +179,6 @@ gulp.task('default', [
'compile', 'compile',
'build', 'build',
'copy', 'copy',
'test',
'watch' 'watch'
]) ])
...@@ -202,10 +187,36 @@ gulp.task('release', (cb) => { ...@@ -202,10 +187,36 @@ gulp.task('release', (cb) => {
'compile', 'compile',
'build', 'build',
'copy', 'copy',
'test'
], cb) ], cb)
}) })
// We run following task inside a NPM script chain and it runs chromedriver
// inside a child process tree.
// Even though we kill this task's process, chromedriver exists throughout
// the lifetime of the original npm script.
gulp.task('start-chromedriver', ['stop-chromedriver'], (cb) => {
const processName = isWindows? 'chromedriver.cmd' : 'chromedriver'
const chromedriver = childProcess.spawn(processName, { stdio: 'inherit' })
const timeoutHandler = setTimeout(() => {
// We need to do this, otherwise this task's process will keep waiting.
process.exit(0)
}, 2000)
})
gulp.task('stop-chromedriver', () => {
try {
if (isWindows) {
childProcess.execSync('taskkill /im chromedriver* /t /f', { stdio: 'ignore' })
} else {
childProcess.execSync('pkill chromedriver', { stdio: 'ignore' })
}
} catch(ex) {
// Do nothing
}
})
// avoid logging to the console // avoid logging to the console
// that we created a notification // that we created a notification
notify_.logLevel(0) notify_.logLevel(0)
......
...@@ -23,13 +23,15 @@ ...@@ -23,13 +23,15 @@
}, },
"scripts": { "scripts": {
"build": "gulp", "build": "gulp",
"pretest": "npm run lint", "release": "gulp release",
"test": "gulp test", "pretestonly": "gulp start-chromedriver",
"html-report": "nyc report --temp-directory=./coverage --reporter=html", "testonly": "cross-env NODE_PATH=test/lib jest \\.test.js",
"jest": "jest --coverage", "posttestonly": "gulp stop-chromedriver",
"coveralls": "nyc report --temp-directory=./coverage --reporter=text-lcov | coveralls", "pretest": "npm run lint && cross-env NODE_ENV=test npm run release",
"test": "npm run testonly -- --coverage --forceExit",
"coveralls": "nyc --instrument=false --source-map=false report --temp-directory=./coverage --reporter=text-lcov | coveralls",
"lint": "standard 'bin/*' 'client/**/*.js' 'examples/**/*.js' 'lib/**/*.js' 'pages/**/*.js' 'server/**/*.js' 'test/**/*.js'", "lint": "standard 'bin/*' 'client/**/*.js' 'examples/**/*.js' 'lib/**/*.js' 'pages/**/*.js' 'server/**/*.js' 'test/**/*.js'",
"prepublish": "gulp release", "prepublish": "npm run test && npm run release",
"precommit": "npm run lint" "precommit": "npm run lint"
}, },
"standard": { "standard": {
...@@ -84,24 +86,34 @@ ...@@ -84,24 +86,34 @@
}, },
"devDependencies": { "devDependencies": {
"babel-eslint": "7.1.1", "babel-eslint": "7.1.1",
"babel-jest": "^18.0.0",
"babel-plugin-istanbul": "^3.0.0",
"babel-plugin-transform-remove-strict-mode": "0.0.2", "babel-plugin-transform-remove-strict-mode": "0.0.2",
"babel-preset-env": "1.1.8", "babel-preset-env": "1.1.8",
"benchmark": "2.1.3", "benchmark": "2.1.3",
"cheerio": "^0.22.0",
"chromedriver": "^2.26.1",
"coveralls": "2.11.15", "coveralls": "2.11.15",
"gulp": "3.9.1", "gulp": "3.9.1",
"gulp-babel": "6.1.2", "gulp-babel": "6.1.2",
"gulp-benchmark": "1.1.1", "gulp-benchmark": "1.1.1",
"gulp-cached": "1.1.1", "gulp-cached": "1.1.1",
"gulp-jest": "^1.0.0",
"gulp-notify": "2.2.0", "gulp-notify": "2.2.0",
"husky": "0.12.0", "husky": "0.12.0",
"jest": "^18.0.0", "jest-cli": "^18.0.0",
"node-fetch": "^1.6.3",
"nyc": "^10.0.0", "nyc": "^10.0.0",
"portfinder": "^1.0.10",
"run-sequence": "1.2.2", "run-sequence": "1.2.2",
"standard": "8.6.0", "standard": "8.6.0",
"webpack-stream": "3.2.0" "wd": "^1.1.1",
"webpack-stream": "3.2.0",
"cross-env": "^3.1.4"
}, },
"jest": { "jest": {
"testEnvironment": "node" "testEnvironment": "node",
"testPathDirs": [
"test/"
]
} }
} }
...@@ -55,6 +55,15 @@ export default class Server { ...@@ -55,6 +55,15 @@ export default class Server {
if (this.hotReloader) { if (this.hotReloader) {
await this.hotReloader.stop() await this.hotReloader.stop()
} }
if (this.http) {
await new Promise((resolve, reject) => {
this.http.close((err) => {
if (err) return reject(err)
return resolve()
})
})
}
} }
defineRoutes () { defineRoutes () {
......
...@@ -161,6 +161,7 @@ export async function serveStaticWithGzip (req, res, path) { ...@@ -161,6 +161,7 @@ export async function serveStaticWithGzip (req, res, path) {
// we don't add gzipped files at runtime. // we don't add gzipped files at runtime.
await fs.stat(gzipPath) await fs.stat(gzipPath)
} catch (ex) { } catch (ex) {
// Handles the error thrown by fs.stat
if (ex.code === 'ENOENT') { if (ex.code === 'ENOENT') {
// Seems like there's no gzipped file. Let's serve the uncompressed file. // Seems like there's no gzipped file. Let's serve the uncompressed file.
return serveStatic(req, res, path) return serveStatic(req, res, path)
......
...@@ -31,8 +31,8 @@ function getPaths (id) { ...@@ -31,8 +31,8 @@ function getPaths (id) {
if (i[i.length - 1] === sep) { if (i[i.length - 1] === sep) {
return [ return [
i + 'index.json', i + 'index.js',
i + 'index.js' i + 'index.json'
] ]
} }
......
throw new Error('This is an expected error')
/* global expect, jasmine, describe, test, beforeAll, afterAll */
'use strict'
import { join } from 'path'
import next from '../dist/server/next'
import pkg from '../package.json'
const dir = join(__dirname, 'fixtures', 'basic')
const app = next({
dir,
dev: true,
staticMarkup: true,
quiet: true
})
jasmine.DEFAULT_TIMEOUT_INTERVAL = 20000
describe('integration tests', () => {
beforeAll(() => app.prepare())
afterAll(() => app.close())
test('renders a stateless component', async () => {
const html = await render('/stateless')
expect(html.includes('<meta charset="utf-8" class="next-head"/>')).toBeTruthy()
expect(html.includes('<h1>My component!</h1>')).toBeTruthy()
})
test('renders a stateful component', async () => {
const html = await render('/stateful')
expect(html.includes('<div><p>The answer is 42</p></div>')).toBeTruthy()
})
test('header helper renders header information', async () => {
const html = await (render('/head'))
expect(html.includes('<meta charset="iso-8859-5" class="next-head"/>')).toBeTruthy()
expect(html.includes('<meta content="my meta" class="next-head"/>')).toBeTruthy()
expect(html.includes('<div><h1>I can haz meta tags</h1></div>')).toBeTruthy()
})
test('css helper renders styles', async () => {
const html = await render('/css')
expect(/\.css-\w+/.test(html)).toBeTruthy()
expect(/<div class="css-\w+">This is red<\/div>/.test(html)).toBeTruthy()
})
test('renders styled jsx', async () => {
const html = await render('/styled-jsx')
expect(html).toMatch(/<style id="__jsx-style-1401785258">p\[data-jsx="1401785258"] {color: blue }[^]+<\/style>/)
expect(html.includes('<div data-jsx="1401785258"><p data-jsx="1401785258">This is blue</p></div>')).toBeTruthy()
})
test('renders properties populated asynchronously', async () => {
const html = await render('/async-props')
expect(html.includes('<p>Diego Milito</p>')).toBeTruthy()
})
test('renders a link component', async () => {
const html = await render('/link')
expect(html.includes('<a href="/about">About</a>')).toBeTruthy()
})
test('error', async () => {
const html = await render('/error')
expect(html).toMatch(/<pre style=".+">Error: This is an expected error\n[^]+<\/pre>/)
})
test('error 404', async () => {
const html = await render('/non-existent')
expect(html).toMatch(/<h1 data-jsx=".+">404<\/h1>/)
expect(html).toMatch(/<h2 data-jsx=".+">This page could not be found\.<\/h2>/)
})
test('finishes response', async () => {
const res = {
finished: false,
end () {
this.finished = true
}
}
const html = await app.renderToHTML({}, res, '/finish-response', {})
expect(html).toBeFalsy()
})
describe('X-Powered-By header', () => {
test('set it by default', async () => {
const req = { url: '/stateless' }
const headers = {}
const res = {
setHeader (key, value) {
headers[key] = value
},
end () {}
}
await app.render(req, res, req.url)
expect(headers['X-Powered-By']).toEqual(`Next.js ${pkg.version}`)
})
test('do not set it when poweredByHeader==false', async () => {
const req = { url: '/stateless' }
const originalConfigValue = app.config.poweredByHeader
app.config.poweredByHeader = false
const res = {
setHeader (key, value) {
if (key === 'X-Powered-By') {
throw new Error('Should not set the X-Powered-By header')
}
},
end () {}
}
await app.render(req, res, req.url)
app.config.poweredByHeader = originalConfigValue
})
})
})
function render (pathname, query = {}) {
return app.renderToHTML({}, {}, pathname, query)
}
...@@ -2,17 +2,17 @@ import React from 'react' ...@@ -2,17 +2,17 @@ import React from 'react'
export default class AsyncProps extends React.Component { export default class AsyncProps extends React.Component {
static async getInitialProps () { static async getInitialProps () {
return await AsyncProps.fetchData() return await fetchData()
}
static fetchData () {
const p = new Promise(resolve => {
setTimeout(() => resolve({ name: 'Diego Milito' }), 10)
})
return p
} }
render () { render () {
return <p>{this.props.name}</p> return <p>{this.props.name}</p>
} }
} }
function fetchData () {
const p = new Promise(resolve => {
setTimeout(() => resolve({ name: 'Diego Milito' }), 10)
})
return p
}
import React from 'react' import React from 'react'
import style from 'next/css' import style from 'next/css'
export default () => <div className={styles}>This is red</div> export default () => <div id='red-box' className={styles}>This is red</div>
const styles = style({ color: 'red' }) const styles = style({ color: 'red' })
export default () => {
throw new Error('This is an expected error')
}
import Link from 'next/link'
export default () => (
<div className='nav-about'>
<Link href='/nav'>
<a>Go Back</a>
</Link>
<p>This is the about page.</p>
</div>
)
import Link from 'next/link'
import { Component } from 'react'
let counter = 0
export default class extends Component {
increase () {
counter++
this.forceUpdate()
}
render () {
return (
<div className='nav-home'>
<Link href='/nav/about'>About</Link>
<p>This is the home.</p>
<div id='counter'>
Counter: {counter}
</div>
<button id='increase' onClick={() => this.increase()}>Increase</button>
</div>
)
}
}
...@@ -13,8 +13,10 @@ export default class Statefull extends Component { ...@@ -13,8 +13,10 @@ export default class Statefull extends Component {
} }
render () { render () {
return <div> return (
<p>The answer is {this.state.answer}</p> <div>
</div> <p id='answer'>The answer is {this.state.answer}</p>
</div>
)
} }
} }
export default () => ( export default () => (
<div> <div>
<p>This is blue</p> <p id='blue-box'>This is blue</p>
<style jsx>{`p { color: blue }`}</style> <style jsx>{`p { color: blue }`}</style>
</div> </div>
) )
/* global describe, it, expect */
import webdriver from 'next-webdriver'
export default (context) => {
describe('Client Navigation', () => {
describe('with <Link/>', () => {
it('should navigate the page', async () => {
const browser = await webdriver(context.appPort, '/nav')
const text = await browser
.elementByCss('a').click()
.waitForElementByCss('.nav-about')
.elementByCss('p').text()
expect(text).toBe('This is the about page.')
await browser.close()
})
it('should navigate via the client side', async () => {
const browser = await webdriver(context.appPort, '/nav')
const counterText = await browser
.elementByCss('#increase').click()
.elementByCss('a').click()
.waitForElementByCss('.nav-about')
.elementByCss('a').click()
.waitForElementByCss('.nav-home')
.elementByCss('#counter').text()
expect(counterText).toBe('Counter: 1')
await browser.close()
})
})
describe('with <a/> tag inside the <Link />', () => {
it('should navigate the page', async () => {
const browser = await webdriver(context.appPort, '/nav/about')
const text = await browser
.elementByCss('a').click()
.waitForElementByCss('.nav-home')
.elementByCss('p').text()
expect(text).toBe('This is the home.')
await browser.close()
})
})
})
}
/* global jasmine, describe, beforeAll, afterAll */
import { join } from 'path'
import {
nextServer,
findPort,
renderViaAPI,
renderViaHTTP
} from 'next-test-utils'
// test suits
import xPoweredBy from './xpowered-by'
import rendering from './rendering'
import misc from './misc'
import clientNavigation from './client-navigation'
const context = {}
context.app = nextServer({
dir: join(__dirname, '../'),
dev: true,
quiet: true
})
jasmine.DEFAULT_TIMEOUT_INTERVAL = 20000
describe('Basic Features', () => {
beforeAll(async () => {
await context.app.prepare()
context.appPort = await findPort()
await context.app.start(context.appPort)
})
afterAll(() => context.app.close())
rendering(context, 'Rendering via API', (p, q) => renderViaAPI(context.app, p, q))
rendering(context, 'Rendering via HTTP', (p, q) => renderViaHTTP(context.appPort, p, q))
xPoweredBy(context)
misc(context)
clientNavigation(context)
})
/* global describe, test, expect */
export default function ({ app }) {
describe('Misc', () => {
test('finishes response', async () => {
const res = {
finished: false,
end () {
this.finished = true
}
}
const html = await app.renderToHTML({}, res, '/finish-response', {})
expect(html).toBeFalsy()
})
})
}
/* global describe, test, expect */
import cheerio from 'cheerio'
export default function ({ app }, suiteName, render) {
async function get$ (path) {
const html = await render(path)
return cheerio.load(html)
}
describe(suiteName, () => {
test('renders a stateless component', async () => {
const html = await render('/stateless')
expect(html.includes('<meta charset="utf-8" class="next-head"/>')).toBeTruthy()
expect(html.includes('My component!')).toBeTruthy()
})
test('renders a stateful component', async () => {
const $ = await get$('/stateful')
const answer = $('#answer')
expect(answer.text()).toBe('The answer is 42')
})
test('header helper renders header information', async () => {
const html = await (render('/head'))
expect(html.includes('<meta charset="iso-8859-5" class="next-head"/>')).toBeTruthy()
expect(html.includes('<meta content="my meta" class="next-head"/>')).toBeTruthy()
expect(html.includes('I can haz meta tags')).toBeTruthy()
})
test('css helper renders styles', async () => {
const $ = await get$('/css')
const redBox = $('#red-box')
expect(redBox.text()).toBe('This is red')
expect(redBox.attr('class')).toMatch(/^css-/)
})
test('renders styled jsx', async () => {
const $ = await get$('/styled-jsx')
const styleId = $('#blue-box').attr('data-jsx')
const style = $(`#__jsx-style-${styleId}`)
expect(style.text()).toMatch(/color: blue/)
})
test('renders properties populated asynchronously', async () => {
const html = await render('/async-props')
expect(html.includes('Diego Milito')).toBeTruthy()
})
test('renders a link component', async () => {
const $ = await get$('/link')
const link = $('a[href="/about"]')
expect(link.text()).toBe('About')
})
test('error', async () => {
const $ = await get$('/error')
expect($('pre').text()).toMatch(/This is an expected error/)
})
test('error 404', async () => {
const $ = await get$('/non-existent')
expect($('h1').text()).toBe('404')
expect($('h2').text()).toBe('This page could not be found.')
})
})
}
/* global describe, test, expect */
import { pkg } from 'next-test-utils'
export default function ({ app }) {
describe('X-Powered-By header', () => {
test('set it by default', async () => {
const req = { url: '/stateless' }
const headers = {}
const res = {
setHeader (key, value) {
headers[key] = value
},
end () {}
}
await app.render(req, res, req.url)
expect(headers['X-Powered-By']).toEqual(`Next.js ${pkg.version}`)
})
test('do not set it when poweredByHeader==false', async () => {
const req = { url: '/stateless' }
const originalConfigValue = app.config.poweredByHeader
app.config.poweredByHeader = false
const res = {
setHeader (key, value) {
if (key === 'X-Powered-By') {
throw new Error('Should not set the X-Powered-By header')
}
},
end () {}
}
await app.render(req, res, req.url)
app.config.poweredByHeader = originalConfigValue
})
})
}
export default () => (
<div>Hello World</div>
)
/* global jasmine, describe, it, expect, beforeAll, afterAll */
import fetch from 'node-fetch'
import { join } from 'path'
import {
nextServer,
nextBuild,
findPort,
renderViaHTTP
} from 'next-test-utils'
const appDir = join(__dirname, '../')
let app
let appPort
jasmine.DEFAULT_TIMEOUT_INTERVAL = 20000
describe('Production Usage', () => {
beforeAll(async () => {
await nextBuild(appDir)
app = nextServer({
dir: join(__dirname, '../'),
dev: false,
quiet: true
})
await app.prepare()
appPort = await findPort()
await app.start(appPort)
})
afterAll(() => app.close())
describe('With basic usage', () => {
it('should render the page', async () => {
const html = await renderViaHTTP(appPort, '/')
expect(html).toMatch(/Hello World/)
})
})
describe('JSON pages', () => {
describe('when asked for a gzipped page', () => {
it('should serve the gzipped page', async () => {
const url = `http://localhost:${appPort}/_next/${app.renderOpts.buildId}/pages`
const res = await fetch(url, { compress: true })
expect(res.headers.get('Content-Encoding')).toBe('gzip')
const page = await res.json()
expect(page.component).toBeDefined()
})
})
describe('when asked for a normal page', () => {
it('should serve the normal page', async () => {
const url = `http://localhost:${appPort}/_next/${app.renderOpts.buildId}/pages`
const res = await fetch(url, { compress: false })
expect(res.headers.get('Content-Encoding')).toBeNull()
const page = await res.json()
expect(page.component).toBeDefined()
})
})
describe('when asked for a page with an unknown encoding', () => {
it('should serve the normal page', async () => {
const url = `http://localhost:${appPort}/_next/${app.renderOpts.buildId}/pages`
const res = await fetch(url, {
compress: false,
headers: {
'Accept-Encoding': 'br'
}
})
expect(res.headers.get('Content-Encoding')).toBeNull()
const page = await res.json()
expect(page.component).toBeDefined()
})
})
})
})
/* global describe, it, expect */
import { join } from 'path'
import resolve from '../../dist/server/resolve'
const dataPath = join(__dirname, '_resolvedata')
describe('Resolve', () => {
it('should resolve a .js path', async () => {
const p = await resolve(join(dataPath, 'one.js'))
expect(p).toBe(join(dataPath, 'one.js'))
})
it('should resolve a .json path', async () => {
const p = await resolve(join(dataPath, 'two.json'))
expect(p).toBe(join(dataPath, 'two.json'))
})
it('should resolve a module without an extension', async () => {
const p = await resolve(join(dataPath, 'one'))
expect(p).toBe(join(dataPath, 'one.js'))
})
it('should resolve a .js module in a directory without /', async () => {
const p = await resolve(join(dataPath, 'aa'))
expect(p).toBe(join(dataPath, 'aa', 'index.js'))
})
it('should resolve a .js module in a directory with /', async () => {
const p = await resolve(join(dataPath, 'aa/'))
expect(p).toBe(join(dataPath, 'aa', 'index.js'))
})
it('should resolve a .json module in a directory', async () => {
const p = await resolve(join(dataPath, 'bb'))
expect(p).toBe(join(dataPath, 'bb', 'index.json'))
})
it('should resolve give priority to index.js over index.json', async () => {
const p = await resolve(join(dataPath, 'cc'))
expect(p).toBe(join(dataPath, 'cc', 'index.js'))
})
it('should throw an error for non existing paths', async () => {
try {
await resolve(join(dataPath, 'aaa.js'))
throw new Error('Should not run this line.')
} catch (ex) {
expect(ex.message).toMatch(/Cannot find module/)
}
})
})
import portFinder from 'portfinder'
import fetch from 'node-fetch'
import qs from 'querystring'
import server from '../../dist/server/next'
import build from '../../dist/server/build'
import _pkg from '../../package.json'
export const nextServer = server
export const nextBuild = build
export const pkg = _pkg
export function findPort () {
return new Promise((resolve, reject) => {
portFinder.getPort((err, port) => {
if (err) return reject(err)
return resolve(port)
})
})
}
export function renderViaAPI (app, pathname, query = {}) {
return app.renderToHTML({}, {}, pathname, query)
}
export function renderViaHTTP (appPort, pathname, query = {}) {
const url = `http://localhost:${appPort}${pathname}?${qs.stringify(query)}`
return fetch(url).then((res) => res.text())
}
import wd from 'wd'
export default async function (appPort, pathname) {
const url = `http://localhost:${appPort}${pathname}`
const browser = wd.promiseChainRemote('http://localhost:9515/')
await browser.init({browserName: 'chrome'}).get(url)
return browser
}
/* global expect, describe, test */
'use strict'
import shallowEquals from '../../lib/shallow-equals'
describe('shallow-equals', () => {
test('returns true if all key/value pairs match', () => {
expect(shallowEquals({
a: 1,
b: 2,
c: 99
}, {
a: 1,
b: 2,
c: 99
})).toBeTruthy()
})
test('returns false if any key/value pair is different', () => {
expect(shallowEquals({
a: 1,
b: 2,
c: 99
}, {
a: 1,
b: 2,
c: 99,
d: 33
})).toBeFalsy()
})
test('returns false if nested objects are contained', () => {
expect(shallowEquals({
a: 1,
b: 2,
c: {}
}, {
a: 1,
b: 2,
c: {}
})).toBeFalsy()
})
})
/* global describe, it, expect */
import shallowEquals from '../../dist/lib/shallow-equals'
describe('Shallow Equals', () => {
it('should be true if both objects are the same', () => {
const a = { aa: 10 }
expect(shallowEquals(a, a)).toBe(true)
})
it('should be true if both objects are similar', () => {
const a = { aa: 10, bb: 30 }
const b = { aa: 10, bb: 30 }
expect(shallowEquals(a, b)).toBe(true)
})
it('should be false if objects have different keys', () => {
const a = { aa: 10, bb: 30 }
const b = { aa: 10, cc: 50 }
expect(shallowEquals(a, b)).toBe(false)
})
it('should be false if objects have same keys but different values', () => {
const a = { aa: 10, bb: 30 }
const b = { aa: 10, bb: 50 }
expect(shallowEquals(a, b)).toBe(false)
})
it('should be false if objects if only they matched deeply', () => {
const a = { aa: 10, bb: { a: 10 } }
const b = { aa: 10, bb: { a: 10 } }
expect(shallowEquals(a, b)).toBe(false)
})
})
This diff is collapsed.
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