如何在Mocha中增加單個測試用例的超時

本文翻譯自:How to increase timeout for a single test case in mocha

I'm submitting a network request in a test case, but this sometimes takes longer than 2 seconds (the default timeout). 我正在測試用例中提交網絡請求,但這有時會花費2秒鐘以上的時間(默認超時)。

How do I increase the timeout for a single test case? 如何增加單個測試用例的超時時間?


#1樓

參考:https://stackoom.com/question/150pT/如何在Mocha中增加單個測試用例的超時


#2樓

Here you go: http://mochajs.org/#test-level 您可以在這裏: http : //mochajs.org/#test-level

it('accesses the network', function(done){
  this.timeout(500);
  [Put network code here, with done() in the callback]
})

For arrow function use as follows: 對於箭頭功能,使用如下:

it('accesses the network', (done) => {
  [Put network code here, with done() in the callback]
}).timeout(500);

#3樓

You might also think about taking a different approach, and replacing the call to the network resource with a stub or mock object. 您可能還會考慮採用其他方法,並用存根或模擬對象替換對網絡資源的調用。 Using Sinon , you can decouple the app from the network service, focusing your development efforts. 使用Sinon ,您可以將應用程序與網絡服務脫鉤,從而集中精力進行開發。


#4樓

從命令行:

mocha -t 100000 test.js

#5樓

(since I ran into this today) (因爲我今天遇到了這個)

Be careful when using ES2015 fat arrow syntax: 使用ES2015粗箭頭語法時要小心:

This will fail : 這將失敗:

it('accesses the network', done => {

  this.timeout(500); // will not work

  // *this* binding refers to parent function scope in fat arrow functions!
  // i.e. the *this* object of the describe function

  done();
});

EDIT: Why it fails: 編輯:爲什麼失敗:

As @atoth mentions in the comments, fat arrow functions do not have their own this binding. 作爲@atoth提到的意見, 胖箭頭函數沒有自己的這種結合。 Therefore, it's not possible for the it function to bind to this of the callback and provide a timeout function. 因此,不可能將it函數綁定到回調並提供超時功能。

Bottom line : Don't use arrow functions for functions that need an increased timeout. 底線 :不要將箭頭功能用於需要增加超時的功能。


#6樓

If you wish to use es6 arrow functions you can add a .timeout(ms) to the end of your it definition: 如果希望使用es6箭頭功能,則可以在it定義的末尾添加.timeout(ms)

it('should not timeout', (done) => {
    doLongThing().then(() => {
        done();
    });
}).timeout(5000);

At least this works in Typescript. 至少這在Typescript中有效。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章