iT邦幫忙

0

Jest 出現 window is not defined的錯誤

  • 分享至 

  • xImage

大家好,
我想請問,我在跑測試npm run test的時候,跑出這個錯誤:

 The error below may be caused by using the wrong test environment, see https://jestjs.io/docs/configuration#testenvironment-string.
    Consider using the "jsdom" test environment.

    ReferenceError: window is not defined

好像是因為Jest測試時,不能使用import導入其他模組,例如axios??
(PS.感謝淺水員大大,axios可以使用import導入到js裡使用了,換jest無法作用QQ)

//theAxios.js
import axios from '../esm/axios.js' //這裡

const fns = {
    fetchData: (num = 1) => {
        return axios.get(`http://localhost:3000/books/${num}`)
    }
}

export default fns;
//theAxios.test.js
import fns from '../js/theAxios'

describe("測試axios返回值", () => {
    let data = {};

    fns.fetchData(1).then(res => {
        data = res;
    });

    test('expect 無法正確取得值', () => {
        expect(data.name).toBe('HappyTime');
    })  
})
//babel.config.json
{
    "presets": [
        [
            "@babel/preset-env",
            {
                "targets": {
                    "node": "current"
                }
            }
        ]
    ]
}

這個要怎麼解決呢?感謝
還是Jest有怎樣的正確使用方法呢?

Jest學習之路好坎坷...
/images/emoticon/emoticon06.gif


使用的版本是"jest": "^28.1.0"

【解決的過程】
(1)發現axios裡面,有用到window跟document的變數!所以必須要有jsdom
(2)發現在node_modules裡,沒有安裝到jest-environment-jsdom(只有安裝jest-environment-node)(還以為安裝jest,所有需要的套件都會自動安裝...)
(3)安裝:npm i jest-environment-jsdom
(4)新增jest.config.js並設定。

module.exports = {
    testEnvironment: 'jest-environment-jsdom'
}

(5)npm run test,OK。
(6)完成環境建置

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

0
neverend327
iT邦新手 5 級 ‧ 2022-05-20 21:59:27
最佳解答

哈囉你好

前陣子我也在寫Jest,有遇到類似的問題。我猜可能是跟JS Dom有關

粗略說就是因為Jest執行環境在Node.js,然後如果沒有JS Dom的話在Node環境下是沒有window、localStorage、document那些東西的

可以參考一下我之前寫的筆記中的第2個問題

啊如果有幫你解決到問題可以幫我的文章按愛心喔,謝謝:)

greenriver iT邦研究生 5 級 ‧ 2022-05-23 13:20:09 檢舉

謝謝。最後發現安裝Jest的時候,沒有安裝jest-environment-jsdom。我安裝完後,再設定jest.config.js後,就可以了

0
albert41
iT邦新手 3 級 ‧ 2022-05-21 00:44:36

如果最後的錯誤訊息一樣是 window is not defined 確實如 neverend327 大大說明的一樣。

另外,按照大大您提供的範例提供個小建議,
API 要在 test case 裡面呼叫,這樣 test case 才夠獨立、單一,
在原本的寫法中,是很有可能 API 還沒收到 response,就已經先觸發 test() 了,
此時很容易會造成錯誤的判斷~

//theAxios.test.js
import fns from '../js/theAxios'

describe("測試axios返回值", () => {
    test('expect 無法正確取得值', () => {
        fns.fetchData(1).then(res => {
            expect(res.name).toBe('HappyTime');
        });
    })  
});

// async/await 寫法:

describe("測試axios返回值", () => {
    test('expect 無法正確取得值', async () => {
        const res = await fns.fetchData(1);
        expect(res.name).toBe('HappyTime');
    })  
});

greenriver iT邦研究生 5 級 ‧ 2022-05-23 13:21:17 檢舉

謝謝,這個很有幫助~
我再測試看看

我要發表回答

立即登入回答