如何在挂上Mocha之前设置超时? [英] How to set timeout on before hook in mocha?

查看:328
本文介绍了如何在挂上Mocha之前设置超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在mocha测试用例中的钩子之前设置超时值.我知道我可以通过在Mocha命令行上添加-t 10000来做到这一点,但这将更改每个测试用例的超时值.我想找到一种以编程方式更改超时的方法,以下是我的代码:

I want to set timeout value on before hook in mocha test cases. I know I can do that by adding -t 10000 on the command line of mocha but this will change every test cases timeout value. I want to find a way to change the timeout programmatically below is my code:

describe('test  ', () => {

  before((done) => {
        this.timeout(10000);
         ...

它将抱怨行this.timeout(1000)未定义timeout.如何在挂机前设置超时.

it will complain about the line this.timeout(1000) that timeout is not defined. How to set the timeout on before hook.

推荐答案

如果您希望超时影响describe中的所有测试,则需要在describe块中而不是在挂钩中设置超时.但是,您需要使用常规"函数作为describe的回调,而不是箭头函数:

You need to set a timeout in your describe block rather than in the hook if you want it to affect all the tests in the describe. However, you need to use a "regular" function as the callback to describe rather than an arrow function:

describe('test', function () {
  this.timeout(10000);

  before(...);

  it(...);
});

在要传递给Mocha的回调中要使用this的所有位置,不能使用箭头功能.您必须使用常规"函数,该函数具有可由Mocha设置的自己的this值.如果使用箭头功能,this的值将不是Mocha想要的值,并且代码将失败.

In all places where you want to use this in a callback you pass to Mocha you cannot use an arrow function. You must use a "regular" function which has its own this value that can be set by Mocha. If you use an arrow function, the value of this won't be what Mocha wants it to be and your code will fail.

可以为您的前钩设置不同的超时时间,但有两点要考虑:

You could set a different timeout for your before hook but there are two things to consider:

  1. 在这里,您还需要使用常规"功能而不是箭头功能,

  1. Here too you'd need to use a "regular" function rather than an arrow function so:

before(function (done) { 
  this.timeout(10000);

  • 这只会为before挂钩设置超时,并且不会影响您的测试.

  • This would set a timeout only for the before hook and would not affect your tests.

    这篇关于如何在挂上Mocha之前设置超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆