Home > other >  Node.js mock context.req.headers.referer
Node.js mock context.req.headers.referer

Time:09-27

I implemented a redirect back to the previously visited page in a project and now have to adjust some tests which are failing because:

Cannot read property 'headers' of undefined
TypeError: Cannot read property 'headers' of undefine

I searched for some time but could not find a good solution or transfer the given answer to my current problem.

Function

export const getServerSideProps: GetServerSideProps<Props> = async (ctx) => {
  ...

  const referer = ctx.req.headers.referer
  let backlink = referer

  if (!referer) {
  ...

    backlink = ...
  }

  return {
    props: {
      ...initialProps.props,
      product,
      backlink,
      ...
  }
}

Test

it('getServerSideProps should return product', async () => {
    mocked(getProductByKey).mockResolvedValueOnce(mockedProducts[0])
    const ctx = {
      query: { productKey: mockedProducts[0].key } as ParsedUrlQuery,
    }

    const result = await getServerSideProps(ctx as GetServerSidePropsContext)
    expect((result as any).props.product).toEqual(mockedProducts[0])
  })

Is there a way to mock the context.req.headers.referer? I would also need this for my own yet-to-be-written test for the redirect back.

CodePudding user response:

Well, it just seems you have to add properties to your variable ctx.

The error is : Cannot read property 'headers' of undefined.

I can see const referer = ctx.req.headers.referer where ctx.req is undefined.

Two possibilities :

  • First : it's a logic error, req or req.headers may be undefined sometimes, you should replace your javascript const referer = ctx.req.headers.referer by const referer = ctx && ctx.req && ctx.req.headers && ctx.req.headers.referer to add checks.

  • Second : it's a test error, req and req.headers will always be defined and your mock is missing it. Just replace in your spec file :

    const ctx = {
      query: { productKey: mockedProducts[0].key } as ParsedUrlQuery,
      req: { headers: {
        referer: 'backlink', // or undefined
      } }
    }

Your error should be fixed and you can edit the referer value (for the moment 'backlink') for other tests if needed.

  • Related