14 importprivate - ranhs/soda-test GitHub Wiki
If you want to access a filed (method or variable) that is defineind in a model but is not exported, you can do this by using rewire on that model. Soda-Test gives you a simple way to do this, just like import the value alough it is not exported.
in the sample file app.ts there is a function that is not expored:
function handleError(res, err): void {...}
To import the private method (or the value of a private variable) you need to define a member varible with the relevent type, and add decorator to it named importPrivate with 2 arguments:
- the relative path to the libraray, where the the private method/vairable is defined
- the name of the private method/variable to import
@importPrivate('./app', 'handleError')
handleError: Function
Note that when importing a varible, if you change its value, it will not have any affect on the varible in model. Also note that if the value of the varible will change in the model, it will not affect the imported varible in your test-case. If you need to set or dynamicly get the value of a private varible use the rewire to do this.
Note that you can use importPrivate decorator in the same way also on test-step method argument.
in app.ts there is a private method you want to test:
function handleError(res, err): void {
if ( err instanceof Error) {
return res.status(400).json({
error: err.message
})
}
return res.status(400).json(err)
}
The follwoing is part of the code in app.test.ts that checks the handleError in the case of an error:
@context('hanldeError')
@stub().returns('done')
jsonStub: SinonStub
@stub().construct({json: 'jsonStub'})
statusStub: SinonStub
@importPrivate('./app', 'handleError')
handleError: (res: express.Response<unknown>, err: Error) => void
res: express.Response<unknown> | { status: SinonStub }
@beforeEach()
beforeEach1(): void {
this.res = { status: this.statusStub }
}
@it('should check error instance and format message')
checkHanldeError1(): TR {
this.handleError(this.res as express.Response<unknown>, new Error('fake'))
expect(this.statusStub).to.have.been.calledWith(400)
expect(this.jsonStub).to.have.been.calledWith({error:'fake'})
}
The method hanldeError, is imported with importPrivate decorator and is called as part of the test-step by accessing the hanldeError member variable that was set to the private method handleError of the app libraray.