在打字稿测试中的模拟中间件调用



我正在尝试为我的打字稿node.js应用程序编写测试。我正在使用摩卡咖啡框架和柴断言库。一切都很好,直到添加自定义中间Wares(例如身份验证检查)。我尝试使用sinon.js嘲笑对此中间件的电话,但是我遇到了麻烦以使其正常工作。任何帮助,将不胜感激。

我的app.ts文件看起来如下:

class App {
public express: express.Application;
constructor() {
this.express = express();
this.routeConfig();
}
private routeConfig(): void {
CustomRouteConfig.init(this.express);
}
}

customRouteconfig文件:

export default class CustomRouteConfig {
static init(app: express.Application) {
app.use('/:something', SomethingMiddleware);
app.use('/:something', SomeAuthenticationMiddleware);
app.use('/:something/route1/endpointOne', ControllerToTest);
app.use(NotFoundHandler);
app.use(ErrorHandler);
}
}

我的contranterTotest.ts文件看起来如下:

export class ControllerToTest {
router  : Router;  
constructor() {   
this.router = Router();
this.registerRoutes();
}
public getData(req: Request, res: Response, next: NextFunction) {
//some logic to call Restful API and return data
}
private registerRoutes() {
this.router.get('/', this.getData.bind(this));
}
}
export default new ControllerToTest().router;

我的东西看起来如下:

export class SomethingMiddleware {
something = (req: Request, res: Response, next: NextFunction) => {
//some logic to check if request is valid, and call next function for either valid or error situation
}
}
export default new SomethingMiddleware().something;

我的这种情况的测试文件如下:

describe('baseRoute', () => {
it('should be json', () => {
return chai.request(app).get('/something/route1/endPointOne')
  .then(res => {
     expect(res.type).to.eql('application/json');
  });
});
});

在这种情况下,使用sinon.js模拟或存根的最佳方法是什么?另外,如果您认为有一种更好的方法可以为此方案编写测试,那也将不胜感激。

我最终使用了Sinon存根。我将它们与摩尔摩卡的功能结合起来,以控制在调用某些外部库时发生的情况。另外,我已经在数据库呼叫和中间件检查中使用了此功能,因为这些单位测试不感兴趣。以下是我如何做的示例。

describe("ControllerToTest", () => {
// Sinon stubs for mocking API calls
before(function () {
    let databaseCallStub= sinon.stub(DatabaseClass, "methodOfInterest", () => {
        return "some dummy content for db call";
    });
    let customMiddlewareStub= sinon.stub(MyCustomMiddleware, "customMiddlewareCheckMethod", () => {
        return true;
    });
    let someExternalLibraryCall= sinon.stub(ExternalLibrary, "methodInExternalLibrary", () => {
        return "some dummy data"
    });
});
after(function () {
    sinon.restore(DatabaseClass.methodOfInterest);
    sinon.restore(MyCustomMiddleware.customMiddlewareCheckMethod);
    sinon.restore(ExternalLibrary.methodInExternalLibrary);
});
it("should return data", () => {
    return chai.request(app).get('/something/route1/endPointOne')
.then(res => {
 expect(res.type).to.eql('application/json');
});
});