jest --init
命令在根目錄創建 jest.config.js文件。具體代碼如下:
module.exports = {
preset: '@vue/cli-plugin-unit-jest',
moduleFileExtensions: [
"js",
"json",
"jsx",
"ts",
"tsx",
"node",
"vue"
],
transform:{
'^.+\\.vue$':'vue-jest',
'.+\\.(css|styl|less|sass|scss|svg|png|jpg)$':'jest-transform-stub',//靜態資源
'.\\.jsx?$':'babel-jest'//js或jsx 語法轉化
},
transformIgnorePatterns:[
'/node-module'
],
moduleNameMapper:{
'^@/(.*)$':'<rootDir>/src/$1'
},
snapshotSerializers: [
'jest-serialzer-vue'//對vue的組件做snapshot測試時使用jest-serializer-vue 第三方模塊對快照做格式化。
],
testMatch:[
'**/tests/unit/**/*.spec.(js|jsx|ts|tsx)|**/__test__/*.(js|jsx|ts|tsx)'//**/tests/unit/**/*.spec.(js|jsx|ts|tsx)自動查找tests/unit下的所有js\jsx文件 當成測試文件執行
],
testURL:'http://localhost/',//虛擬jsDom的路徑 模擬瀏覽器地址
watchPlugins:[
'jest-watch-typeahead/filename',
'jest-watch-typeahead/testname'//交互式提示
]
}
1>、rootDir:其實就是指整個項目的根目錄,也就是最外層的目錄。這里多句嘴,再解釋下path.resolve(__dirname,"../../")的意義,他最終返回的結果是該問見所在的根目錄,簡單來說__dirname返回的是當前目錄,再向上兩層,就是整個項目的根目錄了。
2>、moduleFileExtensions:這個文檔解釋的是“模塊使用的文件擴展名數組,從左往右查找這些文件”。這個參數的意義就是讓jest知道你需要測試覆蓋的文件的擴展名都是什么。
比如:import HelloWorld from '@/components/HelloWorld'
moduleFileExtensions: [
"js",
"json",
"jsx",
"ts",
"tsx",
"node",
"vue"
],
沒有vue的時候,試着運行測試:npm run test:unit 此時就會報錯。如果加上vue就可以正常運行。
3>、transform 語法自動轉化
transform:{
'^.+\\.vue$':'vue-jest',
'.+\\.(css|styl|less|sass|scss|svg|png|jpg)$':'jest-transform-stub',//靜態資源
'.\\.jsx?$':'babel-jest'//js或jsx 語法轉化
}
4>、transformIgnorePatterns 哪些文件夾下的文件不需要轉化。node-module中都是第三方組件,都是已經轉化好的,沒有必要再轉化。
5>、moduleNameMapper 模塊映射,把別名映射到真正的路徑下。如:import HelloWorld from '@/components/HelloWorld'
其中@就是指根目錄下的src。
6>、snapshotSerializers //對vue的組件做snapshot測試時使用jest-serializer-vue 第三方模塊對快照做格式化。