jest测试项目中遇到的报错解决方案

1.报错:window is not defined 解决方法:引入jsdom,在jest.config.js中添加:

testEnvironment: “jsdom”,

2.直接将css(scss,sass)文件导入组件导致的测试程序执行失败 解决方法: 安装jest-css-modules: npm install jest-css-modules --save-dev 在jest配置文件中添加:

"jest": {
   "modulesNameMapper": {
       "\.(css)$": "<rootDir>/node_modules/jest-css-modules"
     }
}

这会告知jest使用jest-css-modules模块替换任何导入文件后缀为.css的文件。 更简单的解决方法:导入的css文件时加个.css后缀 3.安装jest-enzyme后测试程序仍然执行失败 解决方法: 在jest.config.js中添加:

setupFilesAfterEnv: [./node_modules/jest-enzyme/lib/index.js]

4.导入lottie-web, jest测试报错: Cannot set property ‘fillStyle’ of null

解决方法:install jest-canvas-mock

"setupFiles": [
            "<rootDir>/tests/setupJest.ts",
            "jest-canvas-mock"
        ],

others: jest 会在所有真正的测试开始之前执行测试文件里所有的 describe 处理程序. Jest 会按照 test 出现的顺序依次运行所有测试 app.prop(‘属性’) app.instance.func() //可以像props一样直接传方法和数据 simulate,触发时会自动传递e

经验分享 程序员 微信小程序 职场和发展