2018-10-20 17:00:01 +02:00
/* eslint-env jest */
2019-09-04 16:00:54 +02:00
import { loadGetInitialProps } from 'next/dist/next-server/lib/utils'
2018-08-09 19:13:44 +02:00
describe ( 'loadGetInitialProps' , ( ) => {
it ( 'should throw if getInitialProps is defined as an instance method' , ( ) => {
class TestComponent {
2019-11-11 04:24:53 +01:00
getInitialProps ( ) { }
2018-08-09 19:13:44 +02:00
}
const rejectPromise = loadGetInitialProps ( TestComponent , { } )
2019-05-30 03:19:32 +02:00
const error = new Error (
'"TestComponent.getInitialProps()" is defined as an instance method - visit https://err.sh/zeit/next.js/get-initial-props-as-an-instance-method for more information.'
)
2018-08-09 19:13:44 +02:00
return expect ( rejectPromise ) . rejects . toEqual ( error )
} )
2019-07-05 17:00:23 +02:00
it ( 'should resolve to an empty object if getInitialProps is missing' , async ( ) => {
2018-08-09 19:13:44 +02:00
const result = await loadGetInitialProps ( ( ) => { } , { } )
2019-07-05 17:00:23 +02:00
expect ( result ) . toEqual ( { } )
2018-08-09 19:13:44 +02:00
} )
it ( 'should resolve getInitialProps' , async ( ) => {
class TestComponent {
2019-11-11 04:24:53 +01:00
static async getInitialProps ( ) {
2018-08-09 19:13:44 +02:00
return { foo : 1 }
}
}
const result = await loadGetInitialProps ( TestComponent , { } )
expect ( result ) . toEqual ( { foo : 1 } )
} )
it ( 'should be able to return an invalid value if the request was already sent' , async ( ) => {
class TestComponent {
2019-11-11 04:24:53 +01:00
static async getInitialProps ( ) {
2018-08-09 19:13:44 +02:00
return 'invalidValue'
}
}
const ctx = {
res : {
2019-11-11 04:24:53 +01:00
finished : true ,
} ,
2018-08-09 19:13:44 +02:00
}
const result = await loadGetInitialProps ( TestComponent , ctx )
expect ( result ) . toBe ( 'invalidValue' )
} )
2019-05-30 03:19:32 +02:00
it ( "should throw if getInitialProps won't return an object " , ( ) => {
2018-08-09 19:13:44 +02:00
class TestComponent {
2019-11-11 04:24:53 +01:00
static async getInitialProps ( ) { }
2018-08-09 19:13:44 +02:00
}
const rejectPromise = loadGetInitialProps ( TestComponent , { } )
2019-05-30 03:19:32 +02:00
const error = new Error (
'"TestComponent.getInitialProps()" should resolve to an object. But found "undefined" instead.'
)
2018-08-09 19:13:44 +02:00
return expect ( rejectPromise ) . rejects . toEqual ( error )
} )
} )