2

I have problems about Jest. This error happens when I execute "Table.test.js". So I searched this error and found this post unit test raises error because of .getContext() is not implemented And then I imported "jest-canvas-mock" and add "jest" in Package.json to the following in accordance with https://www.npmjs.com/package/jest-canvas-mock. But It wasn't resolved. Please tell me how to resolve. enter image description here

Package.json

{
  "name": "react-frontend",
  "jest": {
    "setupFiles": [
      "jest-canvas-mock"
    ]
  },
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@material-ui/core": "^4.11.2",
    "@material-ui/icons": "^4.11.2",
    "@testing-library/jest-dom": "^5.11.6",
    "@testing-library/user-event": "^12.6.0",
    "axios": "^0.21.0",
    "bootstrap": "^4.5.3",
    "material-table": "^1.69.2",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-scripts": "4.0.1",
    "web-vitals": "^0.2.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@testing-library/react": "^11.2.2",
    "jest-canvas-mock": "^2.3.0",
    "jest-dom": "^4.0.0",
    "react-test-renderer": "^17.0.1"
  }
}

Table.test.js

import React from 'react';
import { render, screen } from '@testing-library/react';
import { Table } from '../../Table';
import 'jest-canvas-mock';

describe('Table', () => {
    test('renders App component', () => {
        render(<Table />);
    });
});

Table.js

import React from 'react';
import MaterialTable from 'material-table';
import CheckListService from '../services/CheckList';
import { useEffect } from 'react'
import { useState } from 'react';
import Typography from '@material-ui/core/Typography';
import Link from '@material-ui/core/Link';
import Box from '@material-ui/core/Box';
import { makeStyles } from '@material-ui/core';


const localizationJapanese = {
    error: "エラー",
    body: {
        emptyDataSourceMessage: "表示するレコードがありません。",
        filterRow: {
            filterPlaceHolder: "",
            filterTooltip: "フィルター",
        },
        editRow: {
            saveTooltip: "保存",
            cancelTooltip: "キャンセル",
            deleteText: "この行を削除しますか?",
        },
        addTooltip: "追加",
        deleteTooltip: "削除",
        editTooltip: "編集",
    },
    header: {
        actions: "アクション",
    },
    grouping: {
        groupedBy: "グループ化:",
        placeholder: "ヘッダーをドラッグ ...",
    },
    pagination: {
        firstTooltip: "最初のページ",
        firstAriaLabel: "最初のページ",
        previousTooltip: "前のページ",
        previousAriaLabel: "前のページ",
        nextTooltip: "次のページ",
        nextAriaLabel: "次のページ",
        labelDisplayedRows: "{from}-{to} 全{count}件",
        labelRowsPerPage: "ページあたりの行数:",
        lastTooltip: "最後のページ",
        lastAriaLabel: "最後のページ",
        labelRowsSelect: "行",
    },
    toolbar: {
        addRemoveColumns: "列の追加、削除",
        nRowsSelected: "{0} 行選択",
        showColumnsTitle: "列の表示",
        showColumnsAriaLabel: "列の表示",
        exportTitle: "出力",
        exportAriaLabel: "出力",
        exportCSVName: "CSV出力",
        exportPDFName: "PDF出力",
        searchTooltip: "検索",
        searchPlaceholder: "検索",
        searchAriaLabel: "検索",
        clearSearchAriaLabel: "クリア",
    },
};

function Copyright() {
    return (
        <Typography variant="body2" color="textSecondary" align="center">
            {'Copyright © '}
            <Link color="inherit" href="https://material-ui.com/">
                株式会社ウィラム. All rights reserved.
        </Link>{' '}
            {new Date().getFullYear()}
            {'.'}
        </Typography>
    );
}

const useStyles = makeStyles({
    root: {
        marginTop: '100px',
        marginBottom: '100px',

    }
});

export const Table = () => {
    const classes = useStyles();
    const [dataAll, setDataAll] = useState([]);
    useEffect(() => {
        CheckListService.getList().then((response) =>
            setDataAll(response.data)
        )
    }, [])

    const columns = [
        {
            title: 'リスト番号', field: 'listNo'
        },
        {
            title: '採用日', field: 'saiyouDate'
        },
        {
            title: 'バージョン', field: 'version'
        },
        {
            title: '種別', field: 'shubetu'
        },
        {
            title: 'ライセンス', field: 'licenseManage'
        },
        {
            title: '用途', field: 'youto'
        },
        {
            title: '備考', field: 'bikou'
        },
        {
            title: '承認者', field: 'authorizer'
        },
        {
            title: '承認日', field: 'approvalDate'
        },
        {
            title: 'URL', field: 'url'
        }
    ]
    return (
        <div>
            <div className="container">
                <div className={classes.root}>
                    <MaterialTable
                        title="使用許可ソフトウェアリスト"
                        data={dataAll}
                        columns={columns}
                        style={{
                            marginTop: '50px',
                            whiteSpace: 'nowrap',
                        }}
                        options={{

                            headerStyle: {
                                backgroundColor: '#75A9FF',
                                color: '#FFF'
                            }

                        }}
                        localization={localizationJapanese}
                    />

                </div>
            </div>
            <Box pt={4}>
                <Copyright />
            </Box>
        </div>
    )


}



PS:Is this correct? This error show up in Console.

We detected setupFilesAfterEnv in your package.json. Remove it from Jest configuration, and put the initialization code in >src/setupTests.js. fThis file will be loaded automatically. setupTest.js

// jest-dom adds custom jest matchers for asserting on DOM nodes.
// allows you to do things like:
// expect(element).toHaveTextContent(/react/i)
// learn more: https://github.com/testing-library/jest-dom
import '@testing-library/jest-dom';
import 'jest-canvas-mock';

const localStorageMock = {
    getItem: jest.fn(),
    setItem: jest.fn(),
    removeItem: jest.fn(),
    clear: jest.fn(),
};
global.localStorage = localStorageMock;


Package.json

{
  "name": "react-frontend",
  "jest": {
    "setupFilesAfterEnv": [
      "<rootDir>/src/setupTests.js"
    ]
  },
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@material-ui/core": "^4.11.2",
    "@material-ui/icons": "^4.11.2",
    "@testing-library/jest-dom": "^5.11.6",
    "@testing-library/user-event": "^12.6.0",
    "axios": "^0.21.0",
    "bootstrap": "^4.5.3",
    "material-table": "^1.69.2",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-scripts": "4.0.1",
    "web-vitals": "^0.2.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@testing-library/react": "^11.2.2",
    "jest-canvas-mock": "^2.3.0",
    "jest-dom": "^4.0.0",
    "react-test-renderer": "^17.0.1"
  }
}
sy-torii
  • 55
  • 2
  • 11
  • 1
    It's not evident that Jest config in package.json is in use. It could be ignored depending on the setup. setupFiles should be added to a config that really affects tests and then it's expected to work. Try to add an import to https://create-react-app.dev/docs/running-tests/#srcsetuptestsjs instead, it's a default location for setupFilesAfterEnv in CRA. – Estus Flask Dec 25 '20 at 08:39
  • Thanks a lot! That problem is resolved. Is it Ok if The follwing shows? Out of the box, Create React App only supports overriding these Jest options: • clearMocks • collectCoverageFrom • coveragePathIgnorePatterns • coverageReporters • displayName • extraGlobals • globalSetup • globalTeardown – sy-torii Dec 25 '20 at 08:59
  • 1
    The message likely means that some config options are ignored. In case it refers to setupFiles, setupTests.js needs to be used instead. – Estus Flask Dec 25 '20 at 09:48
  • Sorry for my poor understanding. I add PS so please confirm it. – sy-torii Dec 26 '20 at 14:01
  • 1
    setupFilesAfterEnv isn't needed in this case, src/setupTests.js is included by default in CRA Jest setup. – Estus Flask Dec 26 '20 at 17:14
  • Thank you for your explanations. I cleared up all problem when I did what you said and restarted console! – sy-torii Dec 27 '20 at 13:25
  • Does this answer your question? [unit test raises error because of .getContext() is not implemented](https://stackoverflow.com/questions/48828759/unit-test-raises-error-because-of-getcontext-is-not-implemented) – Matthias Nov 23 '21 at 21:19

0 Answers0