[英]ReferenceError: VUE_APP_CONFIG is not defined Jest unit tests failing
[英]JEST for Javascript integration tests throwing ReferenceError: fetch is not defined
我有使用 Jest 為 Javascript 代碼編寫集成測試的要求。 但是我看到fetch 沒有定義,即使我也安裝了 node-fetch 。 知道如何解決這個問題嗎?
這是我的package.json
{
"name": "some-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "jest --testRegex='script/integration-tests/.*(int-test))\\.js?$'"
},
"devDependencies": {
"jest": "^28.1.3",
"node-fetch": "^2.6.7",
"uglify-js": "3.16.2"
}
}
/scripts/validator.js
function validate(){
fetch(SOME_UENDPOINT_URL, {
method: 'GET',
mode: 'cors',
credentials: 'include',
headers:{
'content-type': 'application/json',
}
}).then(response => {
return response;
}).then(data => {
});
}
這是我的 JEST 集成腳本。
const{validate} = require('../scripts/validator');
describe('User validation', () => {
test('Should authenticate user', ()=>{
validate();
//some basic assertion follows
});
});
為了使用 fetch 您需要先導入它。 您可以將此語句添加到 validator.js 的頂部。
Fetch 的第 2 版與 require() 兼容,因此將const fetch = require('node-fetch')
添加到 validator.js 的頂部
const fetch = require('node-fetch');
function validate(){
fetch(SOME_UENDPOINT_URL, {
method: 'GET',
mode: 'cors',
credentials: 'include',
headers:{
'content-type': 'application/json',
}
}).then(response => {
return response;
}).then(data => {
});
}
似乎需要導入 node-fetch 。 首先通過將import fetch from 'node-fetch'
添加到 validator.js 的頂部來導入 fetch
import fetch from 'node-fetch';
function validate(){
fetch(SOME_UENDPOINT_URL, {
method: 'GET',
mode: 'cors',
credentials: 'include',
headers:{
'content-type': 'application/json',
}
}).then(response => {
return response;
}).then(data => {
});
}
然后,將"type": "module"
添加到您的 package.json。 --experimental-vm-modules
標志添加到您的 jest 命令中。
{
"name": "some-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"test": "jest --experimental-vm-modules --testRegex='script/integration-tests/.*(int-test))\\.js?$'"
},
"devDependencies": {
"jest": "^28.1.3",
"node-fetch": "^2.6.7",
"uglify-js": "3.16.2"
}
}
最后,如果您希望使用節點運行腳本,則需要添加--experimental-modules
標志。
node --experimental-modules index.js
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.