我用create-react-app创建了一个空应用程序.它在pckage.json和一个示例App.test.js中提供了一个测试脚本.在第一步,我想根据 create-react-app的文档设置测试环境.在我的应用程序中,我将使用localS
让我们说下面的动作进行测试
export const cancel = () => { localStorage.removeItem("MyAppData"); return { type: types.USER_CANCEL}; };
除了酶部分,它还显示了如何初始化localStorage.所以我最终得到了一个setupTests.js文件
import { configure } from "enzyme"; import Adapter from "enzyme-adapter-react-16"; // react-testing-library renders your components to document.body, // this will ensure they're removed after each test. import "react-testing-library/cleanup-after-each"; // this adds jest-dom's custom assertions import "jest-dom/extend-expect"; configure({ adapter: new Adapter() }); const localStorageMock = { getItem: jest.fn(), setItem: jest.fn(), clear: jest.fn() }; global.localStorage = localStorageMock;
这里如果我不从jest或jest-dom或jest-enzyme导入jest,ESLinter会在jest.fn()中显示错误,即未定义jest.当我进口并运行纱线测试时,我得到了
$react-scripts test --env=jsdom FAIL src\App.test.js ● Test suite failed to run TypeError: _jest2.default.fn is not a function at Object.<anonymous> (src/setupTests.js:15:27) at <anonymous>
我真的不从QAs这里和其他论坛获得如何设置localStorage进行测试.
您不需要将jest导入到测试文件中.您应该告诉eslint它应该在文件中预期的是什么,因此它知道哪些全局变量存在.
将其添加到使用jest globals的任何文件的顶部
/* eslint-env jest */