19 aggregation - ranhs/soda-test GitHub Wiki
In the app.ts there is an import of another model:
import { isAuthorized } from './auth'
and latter in the app.ts file, there is the follwoing usages of the isAuthorized method:
app.delete('/user/:id', isAuthorized, async (req, res) => {
...
}
Note that the code does not call the isAuthorized but rater pass the method itself to the delete method that probebly save it (since the isAuthorized method is a middleware) for latter usage.
Since no stub was defined during the load of the app.ts model, the real method of isAuthorized is saved.
Latter on we run running a test-step that need to stub the isAuthorized method. The stubbing replace the implemenation of isAuthorized with the stub in the auth model and in the exports of the auth model, but the method saved by the delete method is not stubbed, and the "real" method is called during the test, alghough we wanted to stub it.
when loading the app.ts model on the first time (on the other times it is not loaded but read from cache) we don't want delete to save the "real" method of isAuthorized (or it could not be stubbed). We want it to load an aggregation method that called the isAuthorized method in the auth modle.
Call the method createAggregation and pass it 2 arguments:
- The model path where the method to aggregate it (same as in the import statement)
- The name of the method to aggregate
- origin - The "real" method that was aggregated.
- restore - a method that restore the method in the exports of the model, back to the "real" method.
As long as isAuthorized is not stubbed, the code will call the "real" method using the saved aggregation method. But if it is stubbed, the stub method will be called.
const isAuthrizedAgr = createAggregation('./auth', 'isAuthorized')
import { app } from './app'
isAuthrizedAgr.restore()
...
@context('DELETE /user/:id')
@stub('./auth', 'isAuthorized').calls((req,res,next)=>next())
authStub: SinonStub
@it('should call auth check function and users.delete on success')
async checkDelete1(@stub('./users', 'deleteUser').resolves('fake_delete') deleteStub: SinonStub): PTR {
const response = await request(app).delete('/user/123')
.expect(200)
...
}