我正在尝试为我的Typescript Node.js应用程序编写测试。我正在使用Mocha框架和Chai断言库。在添加自定义中间件(如身份验证检查)之前,一切正常。我尝试使用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);
}
}
我的ControllerToTest.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;
My SomethingMiddleware看起来如下:
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模拟或存根的最佳方法是什么?此外,如果您认为有更好的方法为此方案编写测试,那么也会受到赞赏。
答案 0 :(得分:0)
我最终使用了sinon存根。我将这些与函数之前和之后的Mocha结合起来,以控制在测试期间调用某些外部库时会发生什么。另外,我在数据库调用和中间件检查中使用了它,因为这些对我的单元测试不感兴趣。以下是我如何做到的一个例子。
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');
});
});