Unverified Commit 71474795 authored by Jan Potoms's avatar Jan Potoms Committed by GitHub

Add eslint-plugin-jest (#13003)

parent 5af38f17
{ {
"root": true, "root": true,
"parser": "babel-eslint", "parser": "babel-eslint",
"plugins": ["react", "react-hooks"], "plugins": ["react", "react-hooks", "jest"],
"env": { "env": {
"browser": true, "browser": true,
"commonjs": true, "commonjs": true,
...@@ -21,6 +21,15 @@ ...@@ -21,6 +21,15 @@
} }
}, },
"overrides": [ "overrides": [
{
"files": ["test/**/*.test.js"],
"extends": ["plugin:jest/recommended"],
"rules": {
"jest/expect-expect": "off",
"jest/no-disabled-tests": "off",
"jest/no-try-expect": "off"
}
},
{ "files": ["**/__tests__/**"], "env": { "jest": true } }, { "files": ["**/__tests__/**"], "env": { "jest": true } },
{ {
"files": ["**/*.ts", "**/*.tsx"], "files": ["**/*.ts", "**/*.tsx"],
......
...@@ -68,6 +68,7 @@ ...@@ -68,6 +68,7 @@
"cross-spawn": "6.0.5", "cross-spawn": "6.0.5",
"escape-string-regexp": "2.0.0", "escape-string-regexp": "2.0.0",
"eslint": "6.8.0", "eslint": "6.8.0",
"eslint-plugin-jest": "23.13.1",
"eslint-plugin-react": "7.18.0", "eslint-plugin-react": "7.18.0",
"eslint-plugin-react-hooks": "2.3.0", "eslint-plugin-react-hooks": "2.3.0",
"execa": "2.0.3", "execa": "2.0.3",
......
...@@ -61,7 +61,7 @@ const runTests = mode => { ...@@ -61,7 +61,7 @@ const runTests = mode => {
) )
.then(() => true) .then(() => true)
.catch(() => false) .catch(() => false)
) ).toBe(true)
}) })
} }
} }
......
...@@ -62,7 +62,7 @@ describe('AMP Usage', () => { ...@@ -62,7 +62,7 @@ describe('AMP Usage', () => {
expect(html).toMatch(/Hello World/) expect(html).toMatch(/Hello World/)
const $ = cheerio.load(html) const $ = cheerio.load(html)
expect($('.abc').length === 1) expect($('.abc')).toHaveLength(1)
}) })
it('should render the page without leaving render target', async () => { it('should render the page without leaving render target', async () => {
......
...@@ -14,26 +14,22 @@ export default function({ app }, suiteName, render, fetch) { ...@@ -14,26 +14,22 @@ export default function({ app }, suiteName, render, fetch) {
describe('_document', () => { describe('_document', () => {
test('It has a custom html class', async () => { test('It has a custom html class', async () => {
const $ = await get$('/') const $ = await get$('/')
expect($('html').hasClass('test-html-props')) expect($('html').hasClass('test-html-props')).toBe(true)
}) })
test('It has a custom body class', async () => { test('It has a custom body class', async () => {
const $ = await get$('/') const $ = await get$('/')
expect($('body').hasClass('custom_class')) expect($('body').hasClass('custom_class')).toBe(true)
}) })
test('It injects custom head tags', async () => { test('It injects custom head tags', async () => {
const $ = await get$('/') const $ = await get$('/')
expect( expect($('head').text()).toMatch('body { margin: 0 }')
$('head')
.text()
.includes('body { margin: 0 }')
)
}) })
test('It passes props from Document.getInitialProps to Document', async () => { test('It passes props from Document.getInitialProps to Document', async () => {
const $ = await get$('/') const $ = await get$('/')
expect($('#custom-property').text() === 'Hello Document') expect($('#custom-property').text()).toBe('Hello Document')
}) })
test('It adds nonces to all scripts and preload links', async () => { test('It adds nonces to all scripts and preload links', async () => {
......
module.exports = "I am sometimes found by tooling. I shouldn't be."
/* eslint-env jest */
import webdriver from 'next-webdriver'
import { waitFor } from 'next-test-utils' /* check, File */
import { readFileSync, writeFileSync } from 'fs'
import { join } from 'path'
export default (context, render) => {
describe('Configuration', () => {
it('should have config available on the client', async () => {
const browser = await webdriver(context.appPort, '/next-config')
const serverText = await browser.elementByCss('#server-only').text()
const serverClientText = await browser
.elementByCss('#server-and-client')
.text()
const envValue = await browser.elementByCss('#env').text()
expect(serverText).toBe('')
expect(serverClientText).toBe('/static')
expect(envValue).toBe('hello')
await browser.close()
})
it('should update css styles using hmr', async () => {
let browser
try {
browser = await webdriver(context.appPort, '/webpack-css')
const pTag = await browser.elementByCss('.hello-world')
const initialFontSize = await pTag.getComputedCss('font-size')
expect(initialFontSize).toBe('100px')
const pagePath = join(
__dirname,
'../',
'components',
'hello-webpack-css.css'
)
const originalContent = readFileSync(pagePath, 'utf8')
const editedContent = originalContent.replace('100px', '200px')
// Change the page
writeFileSync(pagePath, editedContent, 'utf8')
await waitFor(10000)
try {
// Check whether the this page has reloaded or not.
const editedPTag = await browser.elementByCss('.hello-world')
const editedFontSize = await editedPTag.getComputedCss('font-size')
expect(editedFontSize).toBe('200px')
} finally {
// Finally is used so that we revert the content back to the original regardless of the test outcome
// restore the about page content.
writeFileSync(pagePath, originalContent, 'utf8')
}
} finally {
if (browser) {
await browser.close()
}
}
})
// it('should update sass styles using hmr', async () => {
// const file = new File(join(__dirname, '../', 'components', 'hello-webpack-sass.scss'))
// let browser
// try {
// browser = await webdriver(context.appPort, '/webpack-css')
// expect(
// await browser.elementByCss('.hello-world').getComputedCss('color')
// ).toBe('rgba(255, 255, 0, 1)')
// file.replace('yellow', 'red')
// await waitFor(10000)
// await check(
// async () => {
// const tag = await browser.elementByCss('.hello-world')
// const prop = await tag.getComputedCss('color')
// expect(prop).toBe('rgba(255, 0, 0, 1)')
// return 'works'
// },
// /works/
// )
// file.restore()
// await waitFor(10000)
// await check(
// async () => {
// const tag = await browser.elementByCss('.hello-world')
// const prop = await tag.getComputedCss('color')
// expect(prop).toBe('rgba(255, 255, 0, 1)')
// return 'works'
// },
// /works/
// )
// } catch (err) {
// file.restore()
// throw err
// } finally {
// if (browser) {
// await browser.close()
// }
// }
// })
})
}
...@@ -3,16 +3,16 @@ ...@@ -3,16 +3,16 @@
import { join } from 'path' import { join } from 'path'
import { import {
renderViaHTTP, renderViaHTTP,
fetchViaHTTP,
findPort, findPort,
launchApp, launchApp,
killApp, killApp,
File,
checkExpectations,
} from 'next-test-utils' } from 'next-test-utils'
import fetch from 'node-fetch' import fetch from 'node-fetch'
import cheerio from 'cheerio'
// test suits import webdriver from 'next-webdriver'
import rendering from './rendering' import { readFileSync, writeFileSync } from 'fs'
import client from './client'
const context = {} const context = {}
jest.setTimeout(1000 * 60 * 5) jest.setTimeout(1000 * 60 * 5)
...@@ -31,21 +31,167 @@ describe('Configuration', () => { ...@@ -31,21 +31,167 @@ describe('Configuration', () => {
]) ])
}) })
afterAll(() => {
killApp(context.server)
})
async function get$(path, query) {
const html = await renderViaHTTP(context.appPort, path, query)
return cheerio.load(html)
}
it('should disable X-Powered-By header support', async () => { it('should disable X-Powered-By header support', async () => {
const url = `http://localhost:${context.appPort}/` const url = `http://localhost:${context.appPort}/`
const header = (await fetch(url)).headers.get('X-Powered-By') const header = (await fetch(url)).headers.get('X-Powered-By')
expect(header).not.toBe('Next.js') expect(header).not.toBe('Next.js')
}) })
afterAll(() => { test('renders css imports', async () => {
killApp(context.server) let browser
try {
browser = await webdriver(context.appPort, '/webpack-css')
const fontSize = await browser
.elementByCss('.hello-world')
.getComputedCss('font-size')
expect(fontSize).toBe('100px')
} finally {
if (browser) {
await browser.close()
}
}
})
test('renders non-js imports from node_modules', async () => {
let browser
try {
browser = await webdriver(context.appPort, '/webpack-css')
const backgroundColor = await browser
.elementByCss('.hello-world')
.getComputedCss('background-color')
expect(backgroundColor).toBe('rgba(0, 0, 255, 1)')
} finally {
if (browser) {
await browser.close()
}
}
})
test('renders server config on the server only', async () => {
const $ = await get$('/next-config')
expect($('#server-only').text()).toBe('secret')
})
test('renders public config on the server only', async () => {
const $ = await get$('/next-config')
expect($('#server-and-client').text()).toBe('/static')
})
test('renders the build id in development mode', async () => {
const $ = await get$('/build-id')
expect($('#buildId').text()).toBe('development')
}) })
rendering( test('correctly imports a package that defines `module` but no `main` in package.json', async () => {
context, const $ = await get$('/module-only-content')
'Rendering via HTTP', expect($('#messageInAPackage').text()).toBe('OK')
(p, q) => renderViaHTTP(context.appPort, p, q), })
(p, q) => fetchViaHTTP(context.appPort, p, q)
) it('should have config available on the client', async () => {
client(context, (p, q) => renderViaHTTP(context.appPort, p, q)) const browser = await webdriver(context.appPort, '/next-config')
const serverText = await browser.elementByCss('#server-only').text()
const serverClientText = await browser
.elementByCss('#server-and-client')
.text()
const envValue = await browser.elementByCss('#env').text()
expect(serverText).toBe('')
expect(serverClientText).toBe('/static')
expect(envValue).toBe('hello')
await browser.close()
})
it('should update css styles using hmr', async () => {
let browser
try {
browser = await webdriver(context.appPort, '/webpack-css')
const pTag = await browser.elementByCss('.hello-world')
const initialFontSize = await pTag.getComputedCss('font-size')
expect(initialFontSize).toBe('100px')
const pagePath = join(
__dirname,
'../',
'components',
'hello-webpack-css.css'
)
const originalContent = readFileSync(pagePath, 'utf8')
const editedContent = originalContent.replace('100px', '200px')
// Change the page
writeFileSync(pagePath, editedContent, 'utf8')
try {
await checkExpectations(async () => {
// Check whether the this page has reloaded or not.
const editedFontSize = await browser
.elementByCss('.hello-world')
.getComputedCss('font-size')
expect(editedFontSize).toBe('200px')
})
} finally {
// Finally is used so that we revert the content back to the original regardless of the test outcome
// restore the about page content.
writeFileSync(pagePath, originalContent, 'utf8')
await checkExpectations(async () => {
// This also make sure that the change is reverted when the etst ends
const editedFontSize = await browser
.elementByCss('.hello-world')
.getComputedCss('font-size')
expect(editedFontSize).toBe('100px')
})
}
} finally {
if (browser) {
await browser.close()
}
}
})
it('should update sass styles using hmr', async () => {
const file = new File(
join(__dirname, '../', 'components', 'hello-webpack-sass.scss')
)
let browser
try {
browser = await webdriver(context.appPort, '/webpack-css')
expect(
await browser.elementByCss('.hello-world').getComputedCss('color')
).toBe('rgba(255, 255, 0, 1)')
try {
file.replace('yellow', 'red')
await checkExpectations(async () => {
const color = await browser
.elementByCss('.hello-world')
.getComputedCss('color')
expect(color).toBe('rgba(255, 0, 0, 1)')
})
} finally {
file.restore()
await checkExpectations(async () => {
const color = await browser
.elementByCss('.hello-world')
.getComputedCss('color')
expect(color).toBe('rgba(255, 255, 0, 1)')
})
}
} finally {
if (browser) {
await browser.close()
}
}
})
}) })
/* eslint-env jest */
import cheerio from 'cheerio'
export default function({ app }, suiteName, render, fetch) {
async function get$(path, query) {
const html = await render(path, query)
return cheerio.load(html)
}
describe(suiteName, () => {
test('renders css imports', async () => {
const $ = await get$('/webpack-css')
expect($('._46QtCORzC4BWRnIseSbG-').text() === 'Hello World')
})
test('renders non-js imports from node_modules', async () => {
const $ = await get$('/webpack-css')
expect($('._2pRSkKTPDMGLMnmsEkP__J').text() === 'Hello World')
})
test('renders server config on the server only', async () => {
const $ = await get$('/next-config')
expect($('#server-only').text() === 'mySecret')
})
test('renders public config on the server only', async () => {
const $ = await get$('/next-config')
expect($('#server-and-client').text() === '/static')
})
test('renders the build id in development mode', async () => {
const $ = await get$('/build-id')
expect($('#buildId').text() === '-')
})
test('correctly imports a package that defines `module` but no `main` in package.json', async () => {
const $ = await get$('/module-only-content')
expect($('#messageInAPackage').text() === 'OK')
})
})
}
...@@ -22,7 +22,7 @@ describe('Conformance system', () => { ...@@ -22,7 +22,7 @@ describe('Conformance system', () => {
) )
}) })
it('Should warn about sync external sync scripts', async () => { it('Should warn about using polyfill.io for fetch', async () => {
const { stderr } = build const { stderr } = build
expect(stderr).toContain( expect(stderr).toContain(
'[BUILD CONFORMANCE WARNING]: Found polyfill.io loading polyfill for fetch.' '[BUILD CONFORMANCE WARNING]: Found polyfill.io loading polyfill for fetch.'
......
...@@ -257,7 +257,7 @@ describe('Invalid CSS Module Usage in node_modules', () => { ...@@ -257,7 +257,7 @@ describe('Invalid CSS Module Usage in node_modules', () => {
}) })
}) })
describe('Invalid CSS Module Usage in node_modules', () => { describe('Invalid Global CSS Module Usage in node_modules', () => {
const appDir = join(fixturesDir, 'invalid-global-module') const appDir = join(fixturesDir, 'invalid-global-module')
beforeAll(async () => { beforeAll(async () => {
......
...@@ -28,7 +28,7 @@ const runTests = () => { ...@@ -28,7 +28,7 @@ const runTests = () => {
const customErrNo404Match = /You have added a custom \/_error page without a custom \/404 page/ const customErrNo404Match = /You have added a custom \/_error page without a custom \/404 page/
describe('Custom _error', () => { describe('Custom _error', () => {
describe('dev mode', () => { describe('dev mode 1', () => {
let stderr = '' let stderr = ''
beforeAll(async () => { beforeAll(async () => {
...@@ -51,7 +51,7 @@ describe('Custom _error', () => { ...@@ -51,7 +51,7 @@ describe('Custom _error', () => {
}) })
}) })
describe('dev mode', () => { describe('dev mode 2', () => {
let stderr = '' let stderr = ''
beforeAll(async () => { beforeAll(async () => {
......
...@@ -96,19 +96,19 @@ function runTests(dev) { ...@@ -96,19 +96,19 @@ function runTests(dev) {
expect(await browser.elementByCss('h3').text()).toBe('My blog') expect(await browser.elementByCss('h3').text()).toBe('My blog')
}) })
// it('should navigate optional dynamic page', async () => { it.skip('should navigate optional dynamic page', async () => {
// let browser let browser
// try { try {
// browser = await webdriver(appPort, '/') browser = await webdriver(appPort, '/')
// await browser.elementByCss('#view-blog-post-1-comments').click() await browser.elementByCss('#view-blog-post-1-comments').click()
// await browser.waitForElementByCss('p') await browser.waitForElementByCss('p')
// const text = await browser.elementByCss('p').text() const text = await browser.elementByCss('p').text()
// expect(text).toMatch(/blog post.*543.*comment.*\(all\)/i) expect(text).toMatch(/blog post.*543.*comment.*\(all\)/i)
// } finally { } finally {
// if (browser) await browser.close() if (browser) await browser.close()
// } }
// }) })
it('should navigate optional dynamic page with value', async () => { it('should navigate optional dynamic page with value', async () => {
let browser let browser
......
/* eslint-env jest */ /* eslint-env jest */
/* eslint-disable jest/no-identical-title */
import fs from 'fs-extra' import fs from 'fs-extra'
import { join } from 'path' import { join } from 'path'
import { import {
......
...@@ -10,7 +10,7 @@ const nextConfig = path.join(appDir, 'next.config.js') ...@@ -10,7 +10,7 @@ const nextConfig = path.join(appDir, 'next.config.js')
describe('Building Firebase', () => { describe('Building Firebase', () => {
// TODO: investigate re-enabling this test in node 12 environment // TODO: investigate re-enabling this test in node 12 environment
xit('Throws an error when building with firebase dependency with worker_threads', async () => { it.skip('Throws an error when building with firebase dependency with worker_threads', async () => {
await fs.writeFile( await fs.writeFile(
nextConfig, nextConfig,
`module.exports = { experimental: { workerThreads: true } }` `module.exports = { experimental: { workerThreads: true } }`
......
...@@ -71,7 +71,7 @@ function runTests(startServer = nextStart) { ...@@ -71,7 +71,7 @@ function runTests(startServer = nextStart) {
const originalCookies = res.headers.get('set-cookie').split(',') const originalCookies = res.headers.get('set-cookie').split(',')
const cookies = originalCookies.map(cookie.parse) const cookies = originalCookies.map(cookie.parse)
expect(originalCookies.every(c => c.includes('; Secure;'))) expect(originalCookies.every(c => c.includes('; Secure;'))).toBe(true)
expect(cookies.length).toBe(2) expect(cookies.length).toBe(2)
expect(cookies[0]).toMatchObject({ Path: '/', SameSite: 'None' }) expect(cookies[0]).toMatchObject({ Path: '/', SameSite: 'None' })
......
...@@ -49,7 +49,7 @@ describe('TypeScript Features', () => { ...@@ -49,7 +49,7 @@ describe('TypeScript Features', () => {
expect($('body').text()).toMatch(/Hello from a/) expect($('body').text()).toMatch(/Hello from a/)
}) })
it('should resolve the first item in the array first', async () => { it('should resolve the second item as fallback', async () => {
const $ = await get$('/resolve-fallback') const $ = await get$('/resolve-fallback')
expect($('body').text()).toMatch(/Hello from only b/) expect($('body').text()).toMatch(/Hello from only b/)
}) })
...@@ -59,7 +59,7 @@ describe('TypeScript Features', () => { ...@@ -59,7 +59,7 @@ describe('TypeScript Features', () => {
expect($('body').text()).toMatch(/Hello/) expect($('body').text()).toMatch(/Hello/)
}) })
it('should resolve a single matching alias', async () => { it('should resolve a wildcard alias', async () => {
const $ = await get$('/wildcard-alias') const $ = await get$('/wildcard-alias')
expect($('body').text()).toMatch(/world/) expect($('body').text()).toMatch(/world/)
}) })
......
...@@ -50,7 +50,7 @@ const runTests = (serverless = false) => { ...@@ -50,7 +50,7 @@ const runTests = (serverless = false) => {
) )
}) })
it('should error when legacy unstable_getServerProps', async () => { it('should error when legacy unstable_getStaticPaths', async () => {
await fs.writeFile( await fs.writeFile(
indexPage, indexPage,
origIndexPage.replace('getStaticProps', 'getStaticPaths') origIndexPage.replace('getStaticProps', 'getStaticPaths')
......
...@@ -77,7 +77,7 @@ function runTests(startServer = nextStart) { ...@@ -77,7 +77,7 @@ function runTests(startServer = nextStart) {
const originalCookies = res.headers.get('set-cookie').split(',') const originalCookies = res.headers.get('set-cookie').split(',')
const cookies = originalCookies.map(cookie.parse) const cookies = originalCookies.map(cookie.parse)
expect(originalCookies.every(c => c.includes('; Secure;'))) expect(originalCookies.every(c => c.includes('; Secure;'))).toBe(true)
expect(cookies.length).toBe(2) expect(cookies.length).toBe(2)
expect(cookies[0]).toMatchObject({ Path: '/', SameSite: 'None' }) expect(cookies[0]).toMatchObject({ Path: '/', SameSite: 'None' })
...@@ -103,7 +103,7 @@ function runTests(startServer = nextStart) { ...@@ -103,7 +103,7 @@ function runTests(startServer = nextStart) {
const originalCookies = res.headers.get('set-cookie').split(',') const originalCookies = res.headers.get('set-cookie').split(',')
const cookies = originalCookies.map(cookie.parse) const cookies = originalCookies.map(cookie.parse)
expect(originalCookies.every(c => c.includes('; Secure;'))) expect(originalCookies.every(c => c.includes('; Secure;'))).toBe(true)
expect(cookies.length).toBe(2) expect(cookies.length).toBe(2)
expect(cookies[0]).toMatchObject({ Path: '/', SameSite: 'None' }) expect(cookies[0]).toMatchObject({ Path: '/', SameSite: 'None' })
......
...@@ -508,13 +508,13 @@ const runTests = (dev = false, looseMode = false) => { ...@@ -508,13 +508,13 @@ const runTests = (dev = false, looseMode = false) => {
if (dev) { if (dev) {
// TODO: re-enable when this is supported in dev // TODO: re-enable when this is supported in dev
// it('should show error when rewriting to dynamic SSG page', async () => { it.skip('should show error when rewriting to dynamic SSG page', async () => {
// const item = Math.round(Math.random() * 100) const item = Math.round(Math.random() * 100)
// const html = await renderViaHTTP(appPort, `/some-rewrite/${item}`) const html = await renderViaHTTP(appPort, `/some-rewrite/${item}`)
// expect(html).toContain( expect(html).toContain(
// `Rewrites don't support dynamic pages with getStaticProps yet. Using this will cause the page to fail to parse the params on the client for the fallback page` `Rewrites don't support dynamic pages with getStaticProps yet. Using this will cause the page to fail to parse the params on the client for the fallback page`
// ) )
// }) })
it('should not show warning from url prop being returned', async () => { it('should not show warning from url prop being returned', async () => {
const urlPropPage = join(appDir, 'pages/url-prop.js') const urlPropPage = join(appDir, 'pages/url-prop.js')
...@@ -749,7 +749,7 @@ const runTests = (dev = false, looseMode = false) => { ...@@ -749,7 +749,7 @@ const runTests = (dev = false, looseMode = false) => {
await check(() => getBrowserBodyText(browser), /hello /) await check(() => getBrowserBodyText(browser), /hello /)
}) })
it('should show error for invalid JSON returned from getStaticProps on CST', async () => { it('should not show error for invalid JSON returned from getStaticProps on CST', async () => {
const browser = await webdriver(appPort, '/') const browser = await webdriver(appPort, '/')
await browser.elementByCss('#non-json').click() await browser.elementByCss('#non-json').click()
await check(() => getBrowserBodyText(browser), /hello /) await check(() => getBrowserBodyText(browser), /hello /)
......
...@@ -256,7 +256,7 @@ describe('Invalid CSS Module Usage in node_modules', () => { ...@@ -256,7 +256,7 @@ describe('Invalid CSS Module Usage in node_modules', () => {
}) })
}) })
describe('Invalid CSS Module Usage in node_modules', () => { describe('Invalid CSS Global Module Usage in node_modules', () => {
const appDir = join(fixturesDir, 'invalid-global-module') const appDir = join(fixturesDir, 'invalid-global-module')
beforeAll(async () => { beforeAll(async () => {
......
...@@ -33,7 +33,7 @@ describe('TypeScript Features', () => { ...@@ -33,7 +33,7 @@ describe('TypeScript Features', () => {
expect($('body').text()).toMatch(/Hello from a/) expect($('body').text()).toMatch(/Hello from a/)
}) })
it('should resolve the first item in the array first', async () => { it('should resolve the second item in as a fallback', async () => {
const $ = await get$('/resolve-fallback') const $ = await get$('/resolve-fallback')
expect($('body').text()).toMatch(/Hello from only b/) expect($('body').text()).toMatch(/Hello from only b/)
}) })
......
...@@ -365,6 +365,23 @@ export async function check(contentFn, regex, hardError = true) { ...@@ -365,6 +365,23 @@ export async function check(contentFn, regex, hardError = true) {
return false return false
} }
// Runs the provided expectations periodically until they pass or time out
export async function checkExpectations(runExpectations) {
const interval = 250
const timeout = 30000
const startTime = Date.now()
while (true) {
try {
return await runExpectations()
} catch (err) {
if (Date.now() - startTime > timeout) {
throw err
}
}
await waitFor(interval)
}
}
export class File { export class File {
constructor(path) { constructor(path) {
this.path = path this.path = path
......
...@@ -3,10 +3,12 @@ import mitt from 'next/dist/next-server/lib/mitt' ...@@ -3,10 +3,12 @@ import mitt from 'next/dist/next-server/lib/mitt'
describe('mitt', () => { describe('mitt', () => {
describe('With listeners', () => { describe('With listeners', () => {
it('should listen to a event', done => { it('should listen to a event', () => {
const ev = mitt() return new Promise(resolve => {
ev.on('sample', done) const ev = mitt()
ev.emit('sample') ev.on('sample', resolve)
ev.emit('sample')
})
}) })
it('should listen to multiple listeners', () => { it('should listen to multiple listeners', () => {
......
...@@ -86,7 +86,7 @@ describe('next-babel-loader', () => { ...@@ -86,7 +86,7 @@ describe('next-babel-loader', () => {
expect(code).toMatchInlineSnapshot(`"\\"undefined\\";"`) expect(code).toMatchInlineSnapshot(`"\\"undefined\\";"`)
}) })
it('should replace typeof window expression nested', async () => { it('should replace typeof window in === expression nested', async () => {
const code = await babel( const code = await babel(
`function a(){console.log(typeof window === 'undefined')}` `function a(){console.log(typeof window === 'undefined')}`
) )
...@@ -98,29 +98,29 @@ describe('next-babel-loader', () => { ...@@ -98,29 +98,29 @@ describe('next-babel-loader', () => {
expect(code).toMatchInlineSnapshot(`"false;"`) expect(code).toMatchInlineSnapshot(`"false;"`)
}) })
it('should replace typeof window expression top level', async () => { it('should replace typeof window in === expression top level', async () => {
const code = await babel(`typeof window === 'object';`) const code = await babel(`typeof window === 'object';`)
expect(code).toMatchInlineSnapshot(`"true;"`) expect(code).toMatchInlineSnapshot(`"true;"`)
}) })
it('should replace typeof window expression top level', async () => { it('should replace typeof window in !== expression top level', async () => {
const code = await babel(`typeof window !== 'undefined';`) const code = await babel(`typeof window !== 'undefined';`)
expect(code).toMatchInlineSnapshot(`"true;"`) expect(code).toMatchInlineSnapshot(`"true;"`)
}) })
it('should replace typeof window expression top level', async () => { it('should replace typeof window expression !== object top level', async () => {
const code = await babel(`typeof window !== 'object';`) const code = await babel(`typeof window !== 'object';`)
expect(code).toMatchInlineSnapshot(`"false;"`) expect(code).toMatchInlineSnapshot(`"false;"`)
}) })
it('should replace typeof window expression top level', async () => { it('should replace typeof window expression top level serverside', async () => {
const code = await babel(`typeof window !== 'undefined';`, { const code = await babel(`typeof window !== 'undefined';`, {
isServer: true, isServer: true,
}) })
expect(code).toMatchInlineSnapshot(`"false;"`) expect(code).toMatchInlineSnapshot(`"false;"`)
}) })
it('should replace typeof window expression top level', async () => { it('should replace typeof window expression !== object top level serverside', async () => {
const code = await babel(`typeof window !== 'object';`, { const code = await babel(`typeof window !== 'object';`, {
isServer: true, isServer: true,
}) })
...@@ -193,12 +193,12 @@ describe('next-babel-loader', () => { ...@@ -193,12 +193,12 @@ describe('next-babel-loader', () => {
expect(code).toMatchInlineSnapshot(`"if(true){}"`) expect(code).toMatchInlineSnapshot(`"if(true){}"`)
}) })
it('should replace NODE_ENV in statement (prod)', async () => { it('should replace NODE_ENV in === statement (prod)', async () => {
const code = await babel(`if (process.env.NODE_ENV === 'production') {}`) const code = await babel(`if (process.env.NODE_ENV === 'production') {}`)
expect(code).toMatchInlineSnapshot(`"if(true){}"`) expect(code).toMatchInlineSnapshot(`"if(true){}"`)
}) })
it('should replace NODE_ENV in statement (prod)', async () => { it('should replace NODE_ENV in !== statement (prod)', async () => {
const code = await babel(`if (process.env.NODE_ENV !== 'production') {}`) const code = await babel(`if (process.env.NODE_ENV !== 'production') {}`)
expect(code).toMatchInlineSnapshot(`"if(false){}"`) expect(code).toMatchInlineSnapshot(`"if(false){}"`)
}) })
......
...@@ -84,13 +84,13 @@ describe('getSortedRoutes', () => { ...@@ -84,13 +84,13 @@ describe('getSortedRoutes', () => {
).toThrowError(/the same slug name/) ).toThrowError(/the same slug name/)
}) })
it('catches reused param names', () => { it('catches reused param names with catch-all', () => {
expect(() => expect(() =>
getSortedRoutes(['/blog/[id]', '/blog/[id]/[...id]']) getSortedRoutes(['/blog/[id]', '/blog/[id]/[...id]'])
).toThrowError(/the same slug name/) ).toThrowError(/the same slug name/)
}) })
it('catches middle catch-all', () => { it('catches middle catch-all with another catch-all', () => {
expect(() => expect(() =>
getSortedRoutes(['/blog/[...id]/[...id2]']) getSortedRoutes(['/blog/[...id]/[...id2]'])
).toThrowErrorMatchingInlineSnapshot( ).toThrowErrorMatchingInlineSnapshot(
...@@ -98,7 +98,7 @@ describe('getSortedRoutes', () => { ...@@ -98,7 +98,7 @@ describe('getSortedRoutes', () => {
) )
}) })
it('catches middle catch-all', () => { it('catches middle catch-all with fixed route', () => {
expect(() => expect(() =>
getSortedRoutes(['/blog/[...id]/abc']) getSortedRoutes(['/blog/[...id]/abc'])
).toThrowErrorMatchingInlineSnapshot( ).toThrowErrorMatchingInlineSnapshot(
......
...@@ -3312,6 +3312,16 @@ ...@@ -3312,6 +3312,16 @@
"@typescript-eslint/typescript-estree" "2.17.0" "@typescript-eslint/typescript-estree" "2.17.0"
eslint-scope "^5.0.0" eslint-scope "^5.0.0"
"@typescript-eslint/experimental-utils@^2.5.0":
version "2.33.0"
resolved "https://registry.yarnpkg.com/@typescript-eslint/experimental-utils/-/experimental-utils-2.33.0.tgz#000f1e5f344fbea1323dc91cc174805d75f99a03"
integrity sha512-qzPM2AuxtMrRq78LwyZa8Qn6gcY8obkIrBs1ehqmQADwkYzTE1Pb4y2W+U3rE/iFkSWcWHG2LS6MJfj6SmHApg==
dependencies:
"@types/json-schema" "^7.0.3"
"@typescript-eslint/typescript-estree" "2.33.0"
eslint-scope "^5.0.0"
eslint-utils "^2.0.0"
"@typescript-eslint/parser@2.17.0": "@typescript-eslint/parser@2.17.0":
version "2.17.0" version "2.17.0"
resolved "https://registry.yarnpkg.com/@typescript-eslint/parser/-/parser-2.17.0.tgz#627f79586d868edbab55f46a6b183cdc341aea1d" resolved "https://registry.yarnpkg.com/@typescript-eslint/parser/-/parser-2.17.0.tgz#627f79586d868edbab55f46a6b183cdc341aea1d"
...@@ -3335,6 +3345,19 @@ ...@@ -3335,6 +3345,19 @@
semver "^6.3.0" semver "^6.3.0"
tsutils "^3.17.1" tsutils "^3.17.1"
"@typescript-eslint/typescript-estree@2.33.0":
version "2.33.0"
resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-2.33.0.tgz#33504c050ccafd38f397a645d4e9534d2eccbb5c"
integrity sha512-d8rY6/yUxb0+mEwTShCQF2zYQdLlqihukNfG9IUlLYz5y1CH6G/9XYbrxQLq3Z14RNvkCC6oe+OcFlyUpwUbkg==
dependencies:
debug "^4.1.1"
eslint-visitor-keys "^1.1.0"
glob "^7.1.6"
is-glob "^4.0.1"
lodash "^4.17.15"
semver "^7.3.2"
tsutils "^3.17.1"
"@webassemblyjs/ast@1.9.0": "@webassemblyjs/ast@1.9.0":
version "1.9.0" version "1.9.0"
resolved "https://registry.yarnpkg.com/@webassemblyjs/ast/-/ast-1.9.0.tgz#bd850604b4042459a5a41cd7d338cbed695ed964" resolved "https://registry.yarnpkg.com/@webassemblyjs/ast/-/ast-1.9.0.tgz#bd850604b4042459a5a41cd7d338cbed695ed964"
...@@ -7106,6 +7129,13 @@ escodegen@^1.9.1: ...@@ -7106,6 +7129,13 @@ escodegen@^1.9.1:
optionalDependencies: optionalDependencies:
source-map "~0.6.1" source-map "~0.6.1"
eslint-plugin-jest@23.13.1:
version "23.13.1"
resolved "https://registry.yarnpkg.com/eslint-plugin-jest/-/eslint-plugin-jest-23.13.1.tgz#b2ce83f76064ad8ba1f1f26f322b86a86e44148e"
integrity sha512-TRLJH6M6EDvGocD98a7yVThrAOCK9WJfo9phuUb0MJptcrOYZeCKzC9aOzZCD93sxXCsiJVZywaTHdI/mAi0FQ==
dependencies:
"@typescript-eslint/experimental-utils" "^2.5.0"
eslint-plugin-react-hooks@2.3.0: eslint-plugin-react-hooks@2.3.0:
version "2.3.0" version "2.3.0"
resolved "https://registry.yarnpkg.com/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-2.3.0.tgz#53e073961f1f5ccf8dd19558036c1fac8c29d99a" resolved "https://registry.yarnpkg.com/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-2.3.0.tgz#53e073961f1f5ccf8dd19558036c1fac8c29d99a"
...@@ -7149,6 +7179,13 @@ eslint-utils@^1.4.3: ...@@ -7149,6 +7179,13 @@ eslint-utils@^1.4.3:
dependencies: dependencies:
eslint-visitor-keys "^1.1.0" eslint-visitor-keys "^1.1.0"
eslint-utils@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/eslint-utils/-/eslint-utils-2.0.0.tgz#7be1cc70f27a72a76cd14aa698bcabed6890e1cd"
integrity sha512-0HCPuJv+7Wv1bACm8y5/ECVfYdfsAm9xmVb7saeFlxjPYALefjhbYoCkBjPdPzGH8wWyTpAez82Fh3VKYEZ8OA==
dependencies:
eslint-visitor-keys "^1.1.0"
eslint-visitor-keys@^1.0.0, eslint-visitor-keys@^1.1.0: eslint-visitor-keys@^1.0.0, eslint-visitor-keys@^1.1.0:
version "1.1.0" version "1.1.0"
resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-1.1.0.tgz#e2a82cea84ff246ad6fb57f9bde5b46621459ec2" resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-1.1.0.tgz#e2a82cea84ff246ad6fb57f9bde5b46621459ec2"
......
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