如何使用箭头符号设置nodejs超时?

问题描述 投票:0回答:1

我正在运行节点v9.4.0。在我的测试套件中,如何使用箭头符号设置超时。下面

describe('Test Stratum client[callbacks]', () => {
  this.timeout(5000);

  // Test for onConnect getting called
  it('onConnect', (done) => {

导致错误

  _this.timeout(5000);
        ^

TypeError: _this.timeout is not a function

在不改变“describe”行的情况下,我可以用什么语法来设置超时?

node.js unit-testing npm timeout
1个回答
0
投票

您可以将其余部分包装在函数中并使用setTimeout

describe('Test Stratum client[callbacks]', () => {
  setTimeout(() => {
    // Test for onConnect getting called
    it('onConnect', (done) => {
      //The rest of your code, etc etc
    });
  //blah blah blah
  }, 5000);

替代方法

Node.js或JavaScript中没有超时。但是,如果您在异步上下文中工作,则可以使用解决方法:

const timeout = ms => new Promise(res => setTimeout(res, ms));
describe('Test Stratum client[callbacks]', async () => {
  await timeout(5000);
  //etc etc

请注意async在第二行之前的() => {

© www.soinside.com 2019 - 2024. All rights reserved.