Skip to content

Commit

Permalink
fix: Do not call router events in SSR (#419)
Browse files Browse the repository at this point in the history
  • Loading branch information
isaachinman authored Jul 24, 2019
1 parent 46f65d5 commit a2a2075
Show file tree
Hide file tree
Showing 2 changed files with 81 additions and 6 deletions.
73 changes: 73 additions & 0 deletions __tests__/hocs/app-with-translation.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/* eslint-env jest */
import React from 'react'

import i18next from 'i18next'
import { mount } from 'enzyme'
import NextApp, { Container } from 'next/app'

import { appWithTranslation } from '../../src/hocs'
import { localeSubpathOptions } from '../../src/config/default-config'

const mockRouterFn = jest.fn()

const defaultConfig = {
localeSubpaths: localeSubpathOptions.NONE,
allLanguages: ['en'],
lng: 'en',
react: {
wait: true,
useSuspense: false,
},
}
const defaultProps = {
Component: () => (
<div>Test Page</div>
),
router: {
replace: mockRouterFn,
pathname: '/test-path',
},
}

const createApp = async (config = defaultConfig, props = defaultProps) => {
const i18n = i18next.createInstance(config)
await i18n.init()

const appWithTranslationAndContext = appWithTranslation.bind({
config,
i18n,
})
const App = appWithTranslationAndContext(class MyApp extends NextApp {
render() {
const { Component, pageProps } = this.props
return (
<Container>
<Component {...pageProps} />
</Container>
)
}
})

return {
i18n,
tree: mount(<App {...props} />),
}
}

describe('appWithTranslation', () => {
beforeEach(mockRouterFn.mockReset)

it('will call router events in a browser context', async () => {
const { i18n } = await createApp()
process.browser = true
await i18n.changeLanguage('en')
expect(mockRouterFn).toHaveBeenCalledTimes(1)
})

it('will not call router events in a server context', async () => {
const { i18n } = await createApp()
process.browser = false
await i18n.changeLanguage('en')
expect(mockRouterFn).toHaveBeenCalledTimes(0)
})
})
14 changes: 8 additions & 6 deletions src/hocs/app-with-translation.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,15 @@ export default function (WrappedComponent) {
const { pathname, asPath, query } = router
const routeInfo = { pathname, query }

if (process.browser && config.localeSubpaths !== localeSubpathOptions.NONE) {
const { as, href } = lngPathCorrector(config, { as: asPath, href: routeInfo }, lng)
if (as !== asPath) {
router.replace(href, as)
if (process.browser) {
if (config.localeSubpaths !== localeSubpathOptions.NONE) {
const { as, href } = lngPathCorrector(config, { as: asPath, href: routeInfo }, lng)
if (as !== asPath) {
router.replace(href, as)
}
} else {
router.replace({ pathname, query })
}
} else {
router.replace({ pathname, query })
}
})

Expand Down

0 comments on commit a2a2075

Please sign in to comment.