diff --git a/packages/next/shared/lib/router/router.ts b/packages/next/shared/lib/router/router.ts index af1eaf0656..254de431cd 100644 --- a/packages/next/shared/lib/router/router.ts +++ b/packages/next/shared/lib/router/router.ts @@ -1615,7 +1615,7 @@ export default class Router implements BaseRouter { } scrollToHash(as: string): void { - const [, hash] = as.split('#') + const [, hash = ''] = as.split('#') // Scroll to top if the hash is just `#` with no value or `#top` // To mirror browsers if (hash === '' || hash === 'top') { diff --git a/test/integration/router-hash-navigation/pages/index.js b/test/integration/router-hash-navigation/pages/index.js new file mode 100644 index 0000000000..0170d3ea19 --- /dev/null +++ b/test/integration/router-hash-navigation/pages/index.js @@ -0,0 +1,16 @@ +import Link from 'next/link' + +export default function Page() { + return ( +
+
+ + top + + + section link + +
section content
+
+ ) +} diff --git a/test/integration/router-hash-navigation/test/index.test.js b/test/integration/router-hash-navigation/test/index.test.js new file mode 100644 index 0000000000..3e65ed752d --- /dev/null +++ b/test/integration/router-hash-navigation/test/index.test.js @@ -0,0 +1,51 @@ +/* eslint-env jest */ + +import { join } from 'path' +import webdriver from 'next-webdriver' +import { + findPort, + launchApp, + killApp, + nextStart, + nextBuild, +} from 'next-test-utils' + +let app +let appPort +const appDir = join(__dirname, '../') + +function runTests() { + it('scrolls to top when href="/" and url already contains a hash', async () => { + const browser = await webdriver(appPort, '/#section') + expect(await browser.eval(() => window.scrollY)).not.toBe(0) + await browser.elementByCss('#top-link').click() + expect(await browser.eval(() => window.scrollY)).toBe(0) + await browser.close() + }) +} + +describe('router.isReady', () => { + describe('dev mode', () => { + beforeAll(async () => { + appPort = await findPort() + app = await launchApp(appDir, appPort) + }) + afterAll(async () => { + await killApp(app) + }) + + runTests() + }) + + describe('production mode', () => { + beforeAll(async () => { + await nextBuild(appDir) + + appPort = await findPort() + app = await nextStart(appDir, appPort) + }) + afterAll(() => killApp(app)) + + runTests() + }) +})