牛魔王的故事
2022-06-09 11:12:07
我是 Javascript 的新手。我有以下代碼完全按照https://stackoverflow.com/a/58785118 describe('tests', () => { beforeEach(async () => Promise.resolve('foo').then(result => { this.dom = result; }) ); it('works', () => { console.log(this.dom); // => foo }); });運行測試時,它抱怨1) tests "before each" hook for "works": TypeError: Cannot set property 'dom' of undefined我錯過了什么嗎?
2 回答

嗶嗶one
TA貢獻1854條經驗 獲得超8個贊
最簡單的方法是刪除使用this并在describe()回調范圍內聲明一個變量:
describe('tests', () => {
let dom;
beforeEach(async () =>
Promise.resolve('foo').then(result => {
dom = result;
})
);
it('works', () => {
console.log(dom); // => foo
});
});

繁星coding
TA貢獻1797條經驗 獲得超4個贊
您在承諾和測試回調函數中使用箭頭函數。then
it
在箭頭函數之前,每個新函數都根據函數的調用方式定義了自己的 this 值:
在構造函數的情況下是一個新對象。
在嚴格模式函數調用中未定義。
如果函數被稱為“對象方法”,則為基礎對象。
所以你的代碼的問題是在測試的回調箭頭函數this
的范圍內是指describe
塊的父范圍。
箭頭函數沒有自己的
this
. 使用封閉詞法范圍的 this 值;箭頭函數遵循正常的變量查找規則。因此,在搜索當前范圍內不存在的 this 時,箭頭函數最終會從其封閉范圍中找到 this。
作為一種選擇,您可以在塊的父范圍內定義變量并在回調describe
中使用它。beforeAll
it
添加回答
舉報
0/150
提交
取消