2017-02-23 55 views
0

我想設置一些變量首先,執行測試之前, ,我發現這個解決方案,Running Mocha setup before each suite rather than before each test在每次測試之前在摩卡套件中設置變量?

但是,我不知道我可以通過可變進我的回調,他們的方式我做我會得到未定義

makeSuite('hello', (context) => { 
    it('should return',() => { 
     assert.strictEqual(1, 1) 
    }) 
}) 
makeSuite('world', (context) => { 
    it('should return',() => { 
     console.log(context) // undefined 
     assert.strictEqual(1, 1) 
    }) 
}) 

function makeSuite(name: string, cb: (context: any) => any) { 
    let age: string; 
    describe(name,() => { 
     beforeEach(() => { 
      age = '123' 
     }) 

     cb(age); 
    }) 
} 

爲什麼我想將變量傳遞到回調,因爲,我將有一個需要設置在beforeEach鉤許多私有變量的原因,我不想重複我的代碼,所有的測試。

回答

2

傳遞給describe的回調立即打電話,但你的beforeEach掛鉤被測試執行時。因此,當調用cb(age)時,age的值爲undefinedage後來設置爲"123",但cb已經得到它的價值副本,所以它沒有效果。爲了讓cb看到更改,您必須將引用傳遞給您隨後進行變異的對象。事情是這樣的:

makeSuite('world', (context) => { 
    it('should return',() => { 
     console.log(context.age) 
    }) 
}) 

function makeSuite(name, cb) { 
    describe(name,() => { 
     let context = { 
      age: undefined, 
     }; 
     beforeEach(() => { 
      context.age = '123'; 
     }); 

     cb(context); 
    }); 
} 

(我已經使其運行作爲純JavaScript刪除打字稿型註解註釋是不反正解決問題的關鍵。)

+0

非常聰明的解決方案! ;),我確實找到了另一種方式,是注入「摩卡背景」,但我不認爲這是一個好習慣! – Tim

0

還有另一種方法,它就是把一個變量注入mocha context

makeSuite('world', function() { 
    it('should return', function() { 
     // read the variable as shown below 
     console.log((this as any).age); // 123 
    }) 
}) 

function makeSuite(name: string, cb:() => any) { 
    describe(name, function() { 
     beforeEach(function() { 
      // inject the desired variable into the mocha context 
      (this as any).age = 123; 
     }) 

     cb(); 
    }) 
} 

但是,我不認爲是變量注入摩卡方面的一個很好的做法,由@Louis提供的答案會是更好的解決方案

+1

是的,我不喜歡'this',因爲它是由Mocha提供的,它包含了部分公共API和一些私有價值。很多時候爲'this'添加一些東西都會起作用,但有一天會出現一個新版本的Mocha與您選擇的變量衝突。例如,現在設置'this.timeout'或'this.retries'會覆蓋Mocha自己的功能。 – Louis

+0

完全同意!感謝您的不錯的破解! ;) – Tim

相關問題