[英]Variable in outer describe block is undefined when accessing in inner describe block with Mocha test
我有一個如下所示的測試套件:
(注意頂部的accountToPost
變量(在第一個describe
塊下面)
describe('Register Account', function () {
var accountToPost;
beforeEach(function (done) {
accountToPost = {
name: 'John',
email: 'email@example.com',
password: 'password123'
};
done();
});
describe('POST /account/register', function(){
describe('when password_confirm is different to password', function(){
//accountToPost is undefined!
accountToPost.password_confirm = 'something';
it('returns error', function (done) {
//do stuff & assert
});
});
});
});
我的問題是,當我嘗試在嵌套的describe塊中修改accountToPost
時,它是未定義的...
我該怎么做才能解決這個問題?
將賦值保持在原來的位置,但是在beforeEach
回調中包裝,代碼將執行:
beforeEach(function () {
accountToPost.password_confirm = 'something';
});
Mocha加載你的文件並執行它,這意味着在 Mocha實際運行測試套件之前立即執行describe
調用。 這就是它如何計算出你宣布的一系列測試。
我通常只將函數和變量聲明放在我傳遞給describe
的回調體中。 更改測試中使用的對象狀態的所有內容都屬於before
, beforeEach
, after
或afterEach
,或者位於測試本身內部。
知道的另一件事是beforeEach
和afterEach
在前后回調至執行it
調用沒有回調到describe
呼叫。 所以如果你認為你的beforeEach
回調會在describe('POST /account/register', ...
之前執行describe('POST /account/register', ...
這是不正確的。它在it('returns error', ...
之前執行it('returns error', ...
。
這段代碼應該說明我在說什么:
console.log("0");
describe('level A', function () {
console.log("1");
beforeEach(function () {
console.log("5");
});
describe('level B', function(){
console.log("2");
describe('level C', function(){
console.log("3");
beforeEach(function () {
console.log("6");
});
it('foo', function () {
console.log("7");
});
});
});
});
console.log("4");
如果您在此代碼上運行mocha,您將看到以遞增順序輸出到控制台的數字。 我的結構與您的測試套件的結構相同,但添加了我推薦的修復程序。 輸出數字0到4,而Mocha正在確定套件中存在哪些測試。 測試尚未開始。 在測試期間輸出其他數字。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.