我try 在mocha中测试一个中间件. 问题是,在执行它们的回调之前,所有的"it"调用都在等待前一个调用完成.

it(`should trigger pre hook 1`, (done) => {
    use((next) => {
        setTimeout(() => {
            done();
            next();
        }, 1000);
    });
});

it(`should trigger pre hook 2`, (done) => {
    use((next) => {
        setTimeout(() => {
            done();
            next();
        }, 1000);
    });
});

start(() => {
  // middleware done
});

The second it(...) waits for the first to complete.
And thats exactly the problem, since the second use(...) is not called before i fire the start(...) function, so it never gets executed and the test fails.

我如何才能告诉mocha执行所有"it"回调,而不是等待前一个回调完成(或失败)?

推荐答案

try spy而不是done,这样您就可以根据需要布局测试,而不需要依赖mocha来控制流程.

describe('middleware', function(){

    // initialise use/start for this test

    const m1 = sinon.spy()
    const m2 = sinon.spy()
    use((next) => {
        setTimeout(() => {
            m1();
            next();
        }, 1000);
    });
    use((next) => {
        setTimeout(() => {
            m2();
            next();
        }, 1000);
    });

    it(`should process a request through middleware`, function(done){
        start(() => {
            // middleware done
            expect(m1.calledOnce, `m1`).to.equal(true)
            expect(m2.calledOnce, `m2`).to.equal(true)
            done()
        });
    })

})

当您在中间件中有功能代码时,间谍还将允许您判断更复杂的调用场景.

Node.js相关问答推荐

GraphQL MongoDB Mongoose填充字段未获取多个类别

在Node.js下使用PostgreSQL客户端聚合PostgreSQL中的用户定义类型

Mongoose抱怨说,整数是数字,而不是整数

TS 后端开发:prismagenerate找不到已安装的@tsed/prisma包

为什么 Cors 在 NodeJS 中不起作用

仅在 vue 脚本未退出的情况下使用 docker 时出现错误

Nodejs 从链接数组中获取数据并保存到 mongodb

如何通过node下载zip并直接解压zip?

等待不在 Express.js 中处理 res.app.render

多字段传递获取查询失败

仅显示用户在 Reactjs 中使用服务器端发布的帖子是 Node Js、Mongodb

如何更新 MongoDB 中对象数组中的键?

使用新react 18.0.0 的 create-react-app my-app redux 错误

Node.js -Firebase 服务帐户私钥不会解析

Fluxible 中的脱水和再水合代表什么?

将 Heroku App 连接到 Atlas MongoDB 云服务

找不到在 docker compose 环境中运行的 node js 应用程序的模块

yarn 和 npm 的主要区别是什么?

Node.js 中的 PHP exit()/die() 类似功能是什么

如何断言不为空?