【发布时间】:2017-07-27 16:19:45
【问题描述】:
我正在尝试为我的 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);
}
}
自定义路由配置文件:
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 模拟或存根的最佳方式是什么?此外,如果您认为有更好的方法来为这种情况编写测试,那也将不胜感激。
【问题讨论】:
标签: node.js typescript mocha.js sinon chai