1

I've the following code:

import { CreatePageArgs } from 'gatsby';
import { onCreatePage } from './onCreatePage';
jest.mock('gatsby');

describe('on create page', () => {
  test('onCreatePage', () => {
    const pageArgs = {} as CreatePageArgs;
    pageArgs.page.internal.type = 'AnotherType';
    onCreatePage(pageArgs);
  });
});

During the execution I get the following error:

 FAIL  src/onCreatePage.test.ts
  ● on create page › onCreatePage

    TypeError: Cannot read property 'internal' of undefined

       6 |   test('onCreatePage', () => {
       7 |     const pageArgs = {} as CreatePageArgs;
    >  8 |     pageArgs.page.internal.type = 'AnotherType';
         |                   ^
       9 |     onCreatePage(pageArgs);
      10 |   });
      11 | });

      at Object.<anonymous> (src/onCreatePage.test.ts:8:19)

How can I deep instantiate a object from an interface in TypeScript with Jest?

1 Answer 1

1

You can't. Interfaces are a concept in TypeScript that only exist during compile time. They do not exist during runtime, hence Jest has no way of using it to construct an object.

Sign up to request clarification or add additional context in comments.

1 Comment

Hmm.. I've seen this: github.com/marchaos/jest-mock-extended So it seems to be possible. Why isn't it integrated into jest?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.