2017-03-07 4 views
0

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'); 
    }); 
}); 

}); 

何?また、このシナリオのテストを書くためのより良いアプローチがあると思うなら、それも高く評価されます。

答えて

0

私はサイロンスタブを使用しました。これらを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'); 
}); 
}); 
関連する問題