The Issue at Hand
I am currently working on testing the correct handling of errors when a use case function returns a rejected promise along with the appropriate status code.
However, I seem to be encountering an issue where instead of getting a rejected promise, I am facing this error message rather than the expected behavior of the mock function returning a rejected promise:
This is the specific error I'm seeing:
TypeError: Cannot read properties of undefined (reading 'then')
The Script
In my test suite setup, I have the following configuration:
const container = new Container();
describe('Controller Error Tests', () => {
let reportController: ReportController;
let generateReportUseCase: IGenerateReportUseCase = mock<IGenerateReportUseCase>();
container.bind<ReportServiceLocator>(TYPES.ReportServiceLocator).to(ReportServiceLocator);
beforeAll(async () => {
jest.clearAllMocks();
cleanUpMetadata();
dotenv.config();
reportController = new ReportController(container.get<ReportServiceLocator>(Symbol.for("ReportServiceLocator")));
});
it('User held shares report use case throws error', async () => {
let requestObj = httpMocks.createRequest({
cookies: {
token: jwt.sign({ id: 'test' }, process.env.JWT_SECRET_KEY!),
},
query: {
report_type: 'CSV'
}
});
let responseObj = httpMocks.createResponse();
mock(generateReportUseCase).usersHeldShares.mockRejectedValue(new Error('Could not generate report'));
await reportController.userHeldShares(requestObj, responseObj);
expect(responseObj.statusCode).toEqual(500);
})
})
reportController.userHeldShares
is an inversify controller structured like this:
@httpGet('/held-shares')
public async userHeldShares(@request() req: express.Request, @response() res: express.Response){
let jwtSecretKey = process.env.JWT_SECRET_KEY;
let ascending: boolean = req.query.ascending === "false" ? false : true;
let report_type: string = String(req.query.reportformat);
let cookieData = await <IUserDto>jwt.verify(req.cookies.token, jwtSecretKey!);
if(!cookieData.id){
return res.status(401).json({error: 'User not authorised'});
}
return await this.generateReportUseCase.usersHeldShares(cookieData.id!, ascending, report_type)
.then((userDto: IUserDto) => {
res.status(200).json(userDto)
})
.catch((err: Error) => {
res.status(500).json(err);
});
}
Here are the initial lines of
generateReportUseCase.usersHeldShares
, which triggers the error:
usersHeldShares(user_id: string, ascending: boolean, report_type: string): Promise<IUserDto> {
return new Promise(async (resolve, reject) => {
this.tradeReadOnlyRepository.fetch({user_id: user_id}, false)
.then(async trades => {
Expected Outcome
My expectation is that when reaching the line
return await this.generateReportUseCase.usersHeldShares(cookieData.id!, ascending, report_type)
in the inversify controller, it should simply return a rejected promise without executing the actual function logic.