Typescript Node.jsアプリケーションのテストを作成しようとしています。私はモカのフレームワークとチャイアサーションライブラリを使用しています。カスタムミドルウェア(認証チェックなど)が追加されるまで、すべてがうまくいきました。このミドルウェアを呼び出すためにSinon.JSを使ってみましたが、動作させるには問題があります。どんな助けもありがとう。模擬ミドルウェアがTypescriptテストで呼び出す
マイapp.tsファイルには、次のようになります。
class App {
public express: express.Application;
constructor() {
this.express = express();
this.routeConfig();
}
private routeConfig(): void {
CustomRouteConfig.init(this.express);
}
}
CustomRouteConfigファイル:
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;
私SomethingMiddlewareはようになります。
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 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;
このシナリオのための私のテストファイルには、次のようになります。このような状況でSinon.JSモックやスタブを使用するための最良の方法です
describe('baseRoute',() => {
it('should be json',() => {
return chai.request(app).get('/something/route1/endPointOne')
.then(res => {
expect(res.type).to.eql('application/json');
});
});
});
何?また、このシナリオのテストを書くためのより良いアプローチがあると思うなら、それも高く評価されます。