Having some trouble with a test function that uses two stubs. The stubs seem to be working fine, as I can see the spy objects inside when I console.log res.json or next. However, the spy is not being called when I make the assertion. The error message reads "expected spy to have been called at least once but was never called". The program itself works, but I'm struggling with this test. Can anyone provide assistance?
Here is the function in question:
export function createOrUpdateToken(req, res, next) {
const { code, redirect_uri, realm_id, quickbooksAuth } = req.body;
if (!code || !redirect_uri || !realm_id) {
const message = 'Authorization code, Redirect URI and Realm Id are required';
return next(new CustomError('Bad Request', message, 400));
}
return issueRefreshTokenBasedOnAuthorizationCode(
{
redirect_uri,
authorizationCode: code,
authorization: quickbooksAuth,
})
.then((response) => {
const { body: { refresh_token } } = response;
return securityModel.findOneAndUpdate(
{ realmId: realm_id },
{ refreshToken: refresh_token },
{ upsert: true },
(err) => {
if (err) return next(err);
return res.json('Authentication successfull');
});
})
.catch((err) => {
return next(err);
});
}
Here is the corresponding test:
it('Should create or update token', () => {
req.body = {
code: '1234',
redirect_uri: 'www.test.com',
realm_id: '12345',
quickbooksAuth: 'dhajksdas.dsajdosaiudjsa.dsaojpdas'
};
sinon
.stub(intuit, 'issueRefreshTokenBasedOnAuthorizationCode')
.resolves({
body: {
refresh_token: 'hjdklasdashda.dsa.dasdsa.dasddasdas'
}
});
sinon
.stub(securityModel, 'findOneAndUpdate')
.withArgs({ realmId: req.body.realm_id },
{ refreshToken: 'hjdklasdashda.dsa.dasdsa.dasddasdas' })
.yields(null);
createOrUpdateToken(req, res, next);
sinon.assert.called(res.json);
});
Here are the conditions set for the test:
beforeEach(() => {
res = {
json: sinon.spy()
};
next = sinon.spy();
});
afterEach(() => {
sinon.restore();
})