Let say I have a method in class UserService
as below
//userService.ts
async createUser(event: APIGatewayProxyEventV2) {
try {
const input = plainToClass(SignupInput, event.body);
const error = await AppValidationError(input);
if (error) return errorReponse(404, error);
const salt = await getSalt();
const hashedPassword = await getHasedPassword(input.password, salt);
const data = await this.repository.createAccount({
email: input.email,
password: hashedPassword,
phone: input.phone,
userType: "BUYER",
salt,
});
if(!data){
return errorReponse(400, "invalid format")
}
return successReponse(data);
} catch (error) {
return errorReponse(500, error);
}
I would like to verify if the this.repository.createAccount
funtion throws error or be rejected, the catch-block
statment is reached. Here is my spec
//userService.spec.ts
describe("user service", () => {
beforeEach(() => {
sandbox = createSandbox();
userRepo = sandbox.createStubInstance(UserRepository);
userService = new UserService(userRepo);
});
afterEach(() => {
sandbox.restore();
});
it.only("when there is error thrown, Then the errorResponse() should be called", async () => {
const expectedError = new Error("oops");
const spiedErrorResp = sandbox.spy(respUtilts, "errorReponse");
sandbox.stub(passwordUtils, "getSalt").resolves("#salt"); //(depend-1)
sandbox.stub(passwordUtils, "getHasedPassword").resolves("#hash"); //(depend-2)
sandbox
.stub(UserRepository.prototype, "createAccount")
.throws(expectedError); // (1)
await userService.createUser(event1);
sandbox.assert.calledOnce(spiedErrorResp);
sandbox.assert.calledWith(spiedErrorResp, 500, expectedError);
});
});
});
Although the createAccount
(at the line(1) in spec file) is configured to be thrown (or rejected), the running flow does not reach to catch-block
statement (as I debug, the const data
in userService.ts
file is undefined
, so, the flow still be in the try-block
. I have not sure this is the true behavior of sinon; or may I configure wrong something. Would you share your some ideas
Notes that: If I configure for one of two lines in spec file (depend-1, depend-2), the catch-block
in userService.ts
is reached as my expectation