[英]CSS.supports is not defined in Jest test
我嘗試了很多在互聯網上尋找解決我的問題的方法,但是我找不到任何可以幫助我的東西。
我有一個 JS 實用程序文件,可以讓我測試值。 這是組成它的功能之一:
const colorIsValid = (color) => {
if (!color || typeof color !== 'string') {
return false
}
if (CSS !== undefined) {
if (CSS.supports('color', color)) {
return true
}
throw new Error(`The provided color : "${color}" is not valid`)
}
throw new Error('Your navigator do not support CSS Api')
}
export { colorIsValid }
當我在不同的瀏覽器上進行手動測試時,一切正常。 但是,當我使用 Jest 運行測試時,出現以下錯誤:
ReferenceError: CSS is not defined
這是我目前的環境。
// package.json
{
"name": "vue-polygon-grid",
"version": "1.0.0",
"description": "Interactive polygon structure for Vue.js",
"author": {
"name": "Guyomar Alexis",
"email": "contact@ag-dev.fr",
"url": "https://ag-dev.fr/"
},
"main": "dist/data-tables.min.js",
"homepage": "https://github.com/ga-devfront/vue-polygon-grid-private",
"keywords": [
"vue3",
"vuejs",
"vue",
"grid",
"polygon",
"composition"
],
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint",
"test": "jest"
},
"dependencies": {
"core-js": "^3.20.2",
"vue": "^3.0.0"
},
"devDependencies": {
"@babel/core": "^7.16.7",
"@babel/preset-env": "^7.16.8",
"@vue/cli-plugin-babel": "~4.5.15",
"@vue/cli-plugin-eslint": "~4.5.15",
"@vue/cli-service": "~4.5.15",
"@vue/compiler-sfc": "^3.2.26",
"@vue/eslint-config-airbnb": "^6.0.0",
"babel-eslint": "^10.1.0",
"babel-jest": "^27.4.6F",
"eslint": "^7.32.0",
"eslint-plugin-import": "^2.25.4",
"eslint-plugin-jest": "^25.3.4",
"eslint-plugin-vue": "^8.2.0",
"jest": "27.4.7",
"jest-junit": "13.0.0",
"jest-transform-stub": "^2.0.0",
"sass": "^1.38.0",
"sass-loader": "^10"
}
}
// jest.config.js
module.exports = {
clearMocks: true,
collectCoverage: true,
coverageDirectory: 'coverage',
"collectCoverageFrom": [
"**/utility/*.{js,jsx}",
],
coverageReporters: ['html', 'text', 'text-summary', 'cobertura'],
transform: {
'^.+\\.js$': 'babel-jest',
'.+\\.(css|styl|less|sass|scss|png|jpg|jpeg|svg|ttf|woff|woff2)$': 'jest-transform-stub',
},
reporters: [
'default',
['jest-junit', { outputDirectory: 'coverage' }],
],
};
有沒有人有解決方案,所以我可以測試我的方法? 提前感謝您花時間閱讀我。
jest 通過 Node 運行時運行,這意味着沒有瀏覽器 API。 你需要模擬它。 查看笑話setupFiles 。
創建一個設置文件:
global.CSS = {
supports: (k, v) => false,
}
然后使用該設置文件將CSS
object 添加到全局 object 上。
這個答案也可能會有所幫助。
如果你真的必須有 DOM API,你可以包含 package JSDOM 來提供幫助。 在我看來,在大多數情況下,這是不必要的依賴。
從您的問題看來,您只需要運行測試即可。 你真的需要設置全局 CSS object 嗎? 你確定你不是在測試實現細節嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.