Unable to mock document attributes in jsdom when using ts-jest

78 Views Asked by At

I'm using Jest with ts-jest in a jsdom environment. I want to mock the object, which is returned by document.adoptedStyleSheets. This property is not yet supported by jsdom.

I'm unable to mock the property in any way. Every attempt always results in document.adoptedStyleSheets being undefined. In fact, I'm unable to mock anything returned from document. Is the object write-protected?

The most similar question to my post would be this one, however TypeScript with ts-jest is not being used and I assume this is the root of my problem.

My current mocking implementation looks like this, it is executed in a beforeAll()-block:


    Object.defineProperty(document, 'adoptedStyleSheets', {
      // mock
    });

However, the document.adoptedStyleSheets value stays at undefined.

jest.config.js


    /** @type {import('ts-jest').JestConfigWithTsJest} */
    export default {
      preset: 'ts-jest',
      testEnvironment: 'jsdom',
      transform: {
        '^.+\\.tsx?$': ['ts-jest', {
          tsconfig: 'tsconfig.test.json',
        }]
      },
      setupFilesAfterEnv: ['<rootDir>/jest-setup.ts']
    };

jest.setup.ts


    import '@testing-library/jest-dom';

tsconfig.test.json


    {
      "include": [
        ".plasmo/index.d.ts",
        "./**/*.ts",
        "./**/*.tsx",
        "./jest-setup.ts"
      ],
      "compilerOptions": {
        "jsx": "react-jsx",
        "paths": {
          "~*": [
            "./src/*"
          ]
        },
        "baseUrl": ".",
        "esModuleInterop": true
      },
    }

0

There are 0 best solutions below