7
votes

I am writing test case using jest and react-testing-library When i run my test script it throws an error as below

TypeError: Cannot read property 'cwd' of undefined

Now I have tried almost everything to solve this but did not find cause of this

I tried to change config , Even I have run using --no-cache but again it throws the same error

here is my config file

const { defaults } = require("jest-config");

module.exports = {
    testEnvironment: "node",
    // setupFiles: [
    //     "<rootDir>/../apollo-server-env/dist/index.js"
    // ],
    preset: "ts-jest",
    testMatch: null,
    testRegex: ".*test*\\.(ts|tsx|js)$",
    testPathIgnorePatterns: [
        "/node_modules/",
        "/dist/"
    ],
    transform: {
        "\\.(gql|graphql)$": "jest-transform-graphql",
        "\\.(ts|tsx)$": "ts-jest",
        // Use our custom transformer only for the *.js and *.jsx files
        "\\.(js|jsx)?$": "./transform.js",
        // future need to test with
        //  "^.+\\.(js|jsx|ts|tsx)$": "./transform.js",
        // ".+\\.(css|styl|less|sass|scss)$": "jest-css-modules-transform"
    },
    roots: [
        "packages",
        "packages-modules",
        "servers"
    ],
    moduleFileExtensions: [...defaults.moduleFileExtensions,
        "ts",
        "tsx",
        "js",
        "gql",
        "graphql"],
    moduleNameMapper: {
        '^__mocks__/(.*)$': '<rootDir>/../../__mocks__/$1',
        // This regex should match the packages that we want compiled from source
        // through `ts-jest`, as opposed to loaded from their output files in
        // `dist`.
        // We don't want to match `apollo-server-env` and
        // `apollo-engine-reporting-protobuf`, because these don't depend on
        // compilation but need to be initialized from as parto of `prepare`.
        '^(?!apollo-server-env|apollo-engine-reporting-protobuf)(apollo-(?:server|datasource|cache-control|tracing|engine)[^/]*|graphql-extensions)(?:/dist)?((?:/.*)|$)': '<rootDir>/../../packages/$1/src$2'
    },
    transformIgnorePatterns: [
        "/node_modules/(?!(@vscode)/).*/"
    ],
    clearMocks: true,
    globals: {
        __BACKEND_URL__: 'http://localhost:3010',
        __GRAPHQL_URL__: 'http://localhost:8085/graphql',
        /*"ts-jest": {
            tsConfig: "<rootDir>/tsconfig.json",
            //https://github.com/kulshekhar/ts-jest/issues/766,
            "diagnostics": {
                "warnOnly": true
            },
            "babelConfig": true
        }*/
    }
};```

Here is my test file 

`import * as React from 'react';
import {render, cleanup} from 'react-testing-library';
import {EditorComponent} from '../components/editor/editor-component';
import { Provider } from 'react-fela';
import { createRenderer } from 'fela';
import 'jest';
import 'jest-dom/extend-expect';
import { MockedProvider } from 'react-apollo/test-utils';
import {FILE_CONTENT_QUERY} from '../../../files-graphql-client/src/queries/index';

const mocks = [{
    request: {
        query : FILE_CONTENT_QUERY,
    },
    result: {
        data: {
            'getReleaseNotes': {},
        },
    },
}];

describe('<EditorComponent/>', () => {

    let componentObj, felaRenderer, props = {
        subscriber: jest.fn(),
        saveDelayFileChangesMutation: jest.fn(),
        loadFileContent: function () {
          return  new Promise(function(resolve) {
              setTimeout(function() {
                  resolve({data: {loadFileContent: {
                              'loadFileContent': {},
                          }}});
              }, 300);
          });
        },
        openingFiles: [{
            value : 'test',
            encoding: 'utf-8',
            oldValue : 'oldTest',
            deleted : false,
            addIgnore : 'test',
            editorId : 1,
            markdown: false,
            preview : true,
            preOpen : false,
            keepOpen : true,
            status : 'test',
            oversize : false,
            changed : true,
            changedEvent: {},
            diff : true,
            size : 25,
        }] as IContent[],
        allSave: false,
        rootPath: '',
        change: jest.fn(),
        actions: [],
        doneSaveAll: jest.fn(),
        changeEditorSubscribes: jest.fn(),
        updateEditorContent: jest.fn(),
        openDiffEditor: jest.fn(),
        closeConflicts: jest.fn(),
        closeEditor: jest.fn(),
        updateChangedContent: jest.fn(),
        setFinderOptions: jest.fn(),
        onOpenFile: jest.fn(),
        styles: {},
        subscribeToMore: jest.fn(),
    };

    beforeEach(() => {
        felaRenderer = createRenderer();
        componentObj = render(<MockedProvider mocks={mocks}><Provider renderer={felaRenderer}><EditorComponent {...props}/></Provider></MockedProvider>);
    });

    afterEach(cleanup);

});`


3
Usually get the file name and line number where the error was thrown from the error message. As you show no code that tries to access cwd its quite hard to guess what's going on. So maybe you can post the full error message and post the part of your code where the error is thrown. - Andreas Köberle

3 Answers

13
votes

Just install the older version of babel-jest: 22. No need to change the version of jest, latest version can be used. Latest version of babel-jest creates the problem

npm install --save-dev [email protected]

0
votes

Probably the problem is the version of the "babel-jest" module. Try to allineate it with the "jest" module. These are my dependencies in my package.json: ... "babel-jest": "^23", "jest": "22.4.3", ...

0
votes

I had the same issue and the reason was that babel-jest has been upgraded to the latest version without upgrading the rest jest-related modules:

"babel-jest": "^26.6.3",
"jest": "^23.6.0",

In my case upgrading jest to the latest version fixed the issue:

"babel-jest": "^26.6.3",
"jest": "^26.6.3",