Testing catch block via jest mock - unit-testing

I'm trying to test the 'catch' block of an async redux action via jest, but throwing a catch in the mock causes the test as a whole to fail.
My action is as follows:
export function loginUser(username, password) {
return async dispatch => {
dispatch({type: UPDATE_IN_PROGRESS});
try {
let response = await MyRequest.postAsync(
'/login', {username: username, password: password}
);
dispatch({
type: USER_AUTHENTICATED,
username: response.username,
token: response.token,
role: response.role,
id: response.id
});
} catch (error) {
dispatch({type: USER_SIGNED_OUT});
throw error;
} finally {
dispatch({type: UPDATE_COMPLETE});
}
};
}
The test is trying to mock up 'MyRequest.postAsync' to throw an error and thus trigger the catch block, but the test just bails with a 'Failed' message
it('calls expected actions when failed log in', async() => {
MyRequest.postAsync = jest.fn(() => {
throw 'error';
});
let expectedActions = [
{type: UPDATE_IN_PROGRESS},
{type: USER_SIGNED_OUT},
{type: UPDATE_COMPLETE}
];
await store.dispatch(userActions.loginUser('foo', 'bar'));
expect(store.getActions()).toEqual(expectedActions);
});
Is there a way to trigger the catch block to execute in my test via a jest mock function (or any other way for that matter)? Would be annoying to not be able to test a large chunk of code (as all my requests work in the same way).
Thanks in advance for help with this.

I don't know if it's still relevant, but you can do it in this way:
it('tests error with async/await', async () => {
expect.assertions(1);
try {
await store.dispatch(userActions.loginUser('foo', 'bar'));
} catch (e) {
expect(e).toEqual({
error: 'error',
});
}
});
Here is a documentation about error handling

I had the same issue. For me the below works. Wrapping up the await with a try/catch
it('calls expected actions when failed log in', async() => {
MyRequest.postAsync = jest.fn(() => {
throw 'error';
});
let expectedActions = [
{type: UPDATE_IN_PROGRESS},
{type: USER_SIGNED_OUT},
{type: UPDATE_COMPLETE}
];
try {
await store.dispatch(userActions.loginUser('foo', 'bar'));
} catch(e) {
expect(store.getActions()).toEqual(expectedActions);
}
});

I set the instance variable which we will access in our testing function to undefined so that it will go to catch block.
PS : This might not be possible all the times as we might not be having variables all time
class APIStore {
async fetchProductsAPI() {
try {
const products = networkManager.fetch('products')
this.productsStore.setProducts(prodcuts)
}
catch(e) {
this.apiStatus = API_FAILED
this.apiError = e
}
}
}
Test case
it('Check API Error ', async () => {
const toCheckErrorStore = new APIStore()
// Setting products store to undefined so that execution goes to catch block
toCheckErrorStore.productsStore = undefined
await toCheckErrorStore.fetchProductsAPI()
expect(toCheckErrorStore.apiStatus).toBe(API_FAILED)
expect(toCheckErrorStore.apiError).toEqual(errorObjectIWantToCompareWith)
}

Related

Jest: Matcher error: expected value must be a function

I'm using NestJS with Jest and getting Matcher error: expected value must be a function error when run following unit test. I have set invalid email in mockBody. Did I missed anything here?
app.service.ts
#Injectable()
export class UserService {
constructor(private emailService: EmailService) {}
async registerUserInquiry(user: UserDto): Promise<{ email: string }> {
try {
await sendEmail(user);
} catch (error) {
throw new HttpException('Something went wrong!', HttpStatus.BAD_REQUEST);
}
return {
email: user.email,
};
}
}
app.service.spec.ts
describe("registerUser()", () => {
it("Should throw bad request error when passing invalid data", async () => {
const mockBody: UserDto = {
name: "John Doe",
message: "Example inquiry message",
email: "#example",
mobile: "+60121234567",
};
expect(async () => await service.registerUserInquiry(mockBody)).toThrow(
new HttpException("Something went wrong!", HttpStatus.BAD_REQUEST)
);
});
});
email.config.ts
export const sendEmail = async (user: User) => {
const transporter = nodemailer.createTransport({
... // service & auth
});
const options = {
... // email info
};
await transporter.sendMail(options, function (error, info) {
try {
console.info(error);
return info;
} catch (error) {
console.error(error);
throw error;
}
});
};
Error:
Instead of this
expect(async () => await service.registerUserInquiry(mockBody)).toThrow(
new HttpException("Something went wrong!", HttpStatus.BAD_REQUEST)
);
Try this one
await except(service.registerUserInquiry(mockBody)).rejects.toThrowError(...)
Your function is a promise which means it is not throwing an error but instead it rejects.

Jest - Mock promisified SQS calls

Let's assume that I have a QueueClass with a method send, that gets some data as parameter
which then sends to a SQS queue.
I want to write 2 tests:
One that tests that the MessageBody and QueueUrl keys have the expected values passed in.
One that in case of error an exception gets thrown.
The method to be tested looks like this:
My send method:
async send(data) {
return SQS.sendMessage({
MessageBody: JSON.stringify(data),
QueueUrl: 'queue_url_here',
})
.promise()
.catch((error) => {
// Throw exception ...
});
}
The test I have for that method:
const aws = require('aws-sdk');
jest.mock('aws-sdk', () => {
const SQSMocked = {
sendMessage: jest.fn().mockReturnThis(),
promise: jest.fn(),
};
return {
SQS: jest.fn(() => SQSMocked),
};
});
sqs = new aws.SQS();
test('my test', async () => {
const data = {};
await QueueClass.send(data);
expect(sqs.sendMessage).toHaveBeenCalledWith({
MessageBody: JSON.stringify(data),
QueueUrl: 'queue_url_here',
});
});
That test gives me the following error:
TypeError: Cannot read property 'catch' of undefined
I did try adding catch: jest.fn() to the SQSMocked object, the exact same way I do with promise, but kept getting the same error.
The thing is that when I change the method that I am trying to test so it uses try-catch block instead of .promise() and .catch() :
async send(data) {
try {
return SQS.sendMessage({
MessageBody: JSON.stringify(data),
QueueUrl: 'queue_url_here',
});
} catch (error) {
// Throw exception ...
}
}
my test passes, so that makes me think that this is not necessarily an issue about properly mocking the SQS.
Any ideas why when using .promise() and .catch() my test fails ?
Also how could I test a case where an Error gets thrown by the queue ?
I would like to be able to do something like this:
await expect(sqs.sendMessage)
.resolves
.toEqual(...);
OR
await expect(sqs.sendMessage)
.rejects
.toThrowError(new Error('Some error thrown.'));
promise is stubbed and returns undefined, this is the reason why it doesn't return a promise that could be chained. It's supposed to return a promise, as the name suggests.
Since values may be different in different tests, it's better to expose it as a variable. sendMessage can be exposed as well for assertions:
const mockPromiseFn = jest.fn();
const mockSendMessage = jest.fn().mockReturnThis();
jest.mock('aws-sdk', () => {
return {
SQS: jest.fn().mockReturnValue({
sendMessage: mockSendMessage,
promise: mockPromiseFn
})
};
});
It doesn't make sense to test it with await expect(sqs.sendMessage).rejects... because it tests the code you've just written.
It likely should be:
mockPromiseFn.mockRejectedValue(new Error(...));
await expect(QueueClass.send(data)).rejects.toThrowError(...);
expect(mockSendMessage).toBeCalledWith(...);
This is potentially a mistake:
async send(data) {
try {
return SQS.sendMessage(...);
} catch (error) {
// Throw exception ...
}
}
try..catch is unable to catch asynchronous errors from async return, also sendMessage return value wasn't converted to a promise.
It should be:
async send(data) {
try {
return await SQS.sendMessage(...).promise();
} catch (error) {
// Throw exception ...
}
}
duplicate questions
How to mock AWS sqs call for unit testing
just add the method around to be called like so...
class EventService {
static async sendFifoMessage(
url,
message,
groupId,
dedupeId,
) {
const sqsMessageRequest = {
QueueUrl: url,
MessageBody: JSON.stringify(message),
MessageGroupId: groupId,
};
if (!!dedupeId) {
sqsMessageRequest.MessageDeduplicationId = dedupeId;
}
return await new SQS().sendMessage(sqsMessageRequest).promise();
}
}
import AWS = require('aws-sdk');
const URL = 'URL';
const MESSAGE = 'MESSAGE';
const GROUP_ID = 'GROUP_ID';
const DEDUPE_ID = 'DEDUPE_ID';
const BAD_REQUEST = 'BAD_REQUEST';
jest.mock('aws-sdk', () => {
const SQSMocked = {
sendMessage: jest.fn().mockReturnThis(),
promise: jest.fn(),
};
return {
SQS: jest.fn(() => SQSMocked),
};
});
const sqs = new AWS.SQS({
region: 'us-east-1',
});
describe('EventService', () => {
beforeEach(() => {
(sqs.sendMessage().promise as jest.MockedFunction < any > ).mockReset();
});
afterAll(() => {
jest.clearAllMocks();
jest.restoreAllMocks();
jest.resetAllMocks();
});
describe('sendFifoMessage', () => {
const messageResult = {
QueueUrl: URL,
MessageBody: JSON.stringify(MESSAGE),
MessageGroupId: GROUP_ID,
MessageDeduplicationId: DEDUPE_ID,
};
it('sendMessage successfully', async() => {
(sqs.sendMessage().promise as jest.MockedFunction < any > ).mockResolvedValueOnce('mocked data');
await EventService.sendFifoMessage(URL, MESSAGE, GROUP_ID, DEDUPE_ID);
expect.assertions(2);
expect(sqs.sendMessage).toBeCalledWith(messageResult);
expect(sqs.sendMessage().promise).toBeCalledTimes(1);
});
it('sendMessage throws', async() => {
(sqs.sendMessage().promise as jest.MockedFunction < any > ).mockRejectedValueOnce(BAD_REQUEST);
expect(async() => await EventService.sendFifoMessage(URL, MESSAGE, GROUP_ID, DEDUPE_ID)).rejects.toThrowError(
new Error(BAD_REQUEST),
);
expect(sqs.sendMessage).toBeCalledWith(messageResult);
expect(sqs.sendMessage().promise).toBeCalledTimes(1);
});
});
});

Cannot log after tests are done in jestjs

I have written test cases for signin API using jest. After completing all five test of a test suit jest give me following error in log.
Can any body tell Why it is So and how to fix it?
CODE:(signup.test.ts)
import request from 'supertest';
import { TYPES } from '../src/inversify.types'
import { Application } from '../src/app/Application'
import { container } from '../src/inversify.config'
import dotenv from 'dotenv'
import { RESPONSE_CODE } from '../src/utils/enums/ResponseCode'
import { RESPONSE_MESSAGES } from '../src/utils/enums/ResponseMessages'
import { UserSchema } from '../src/components/user/User';
// import jwt from 'jsonwebtoken';
var application: Application
describe("POST / - SIGNUP endpoint", () => {
// var testusers: any;
//This hook is executed before running all test cases, It will make application instance, make it to listen
// on it on port 3000 and add test document in DB
beforeAll(async () => {
// Make enviroment variables available throughout the application
dotenv.config();
// Getting application instance using iversify container
application = container.get<Application>(TYPES.Application);
// Initialize frontside of application
await application.bootstrap();
// Starting Application server on given port
await application.listen(3000);
});
afterAll(
//This hook is executed after running all test cases and delete test document in database
async () =>{
const res = await UserSchema.deleteMany({ Name: { $in: [ "Test User", "Test" ] } });
// `0` if no docs matched the filter, number of docs deleted otherwise
console.log('---------------------->>>>>>>>>>>>>>>>>>>', (res as any).deletedCount);
}
)
it("Signup for user that don\'t exists", async () => {
const response = await request(application.getServer()).post('/user/signup')
.send({
"Email": JSON.parse(process.env.TEST_USER).Email,
"Name": "Test User",
"Password": process.env.TEST_ACCOUNTS_PASSWORD
})
expect(response.status).toBe(RESPONSE_CODE.CREATED);
expect(JSON.parse(response.text)).toEqual(expect.objectContaining({
Message: RESPONSE_MESSAGES.ADDED_SUCESSFULLY,
Data: expect.objectContaining({
Name: 'Test User',
Country: '',
PhoneNumber: '',
// Password: '$2b$10$nIHLW/SA73XLHoIcND27iuODFAArOvpch6FL/eikKT78qbShAl6ry',
Dob: '',
Role: 'MEMBER',
IsEmailVerified: false,
IsBlocked: 'ACTIVE',
IsTokenSent: false,
twoFAStatus: false,
// _id: '5c812e2715e0711b98260fee',
Email: JSON.parse(process.env.TEST_USER).Email
})
})
);
console.log('*** Signup for user that don\'t exists *** response', response.text, 'response status', response.status);
});
it("Signup for user that exists", async () => {
const response = await request(application.getServer()).post('/user/signup')
.send({
"Email": JSON.parse(process.env.TEST_USER).Email,
"Name": "Test User",
"Password": process.env.TEST_ACCOUNTS_PASSWORD
})
expect(response.status).toBe(RESPONSE_CODE.CONFLICT);
expect(JSON.parse(response.text)).toEqual({
Message: RESPONSE_MESSAGES.ALREADY_EXISTS
})
console.log('*** Signup for user that don\'t exists *** response', response.text, 'response status', response.status);
});
});
Jest did not exit one second after the test run has completed.
This usually means that there are asynchronous operations that weren't
stopped in your tests. Consider running Jest with
--detectOpenHandles to troubleshoot this issue.
Cannot log after tests are done. Did you forget to wait for something
async in your test?
Attempted to log "{ accepted: [ 'unverifiedtestuser#abc.com' ],
rejected: [],
envelopeTime: 621,
messageTime: 867,
messageSize: 906,
response: '250 2.0.0 OK 1551945300 f6sm5442066wrt.87 - gsmtp',
envelope:
{ from: 'abc#gmail.com',
to: [ 'unverifiedtestuser#abc.com' ] },
messageId: '<45468449-b5c8-0d86-9404-d55bb5f4g6a3#gmail.com>' }".
at CustomConsole.log (node_modules/jest-util/build/CustomConsole.js:156:10)
at src/email/MailHandler.ts:2599:17
at transporter.send.args (node_modules/nodemailer/lib/mailer/index.js:226:21)
at connection.send (node_modules/nodemailer/lib/smtp-transport/index.js:247:32)
at callback (node_modules/nodemailer/lib/smtp-connection/index.js:435:13)
at stream._createSendStream (node_modules/nodemailer/lib/smtp-connection/index.js:458:24)
at SMTPConnection._actionSMTPStream (node_modules/nodemailer/lib/smtp-connection/index.js:1481:20)
at SMTPConnection._responseActions.push.str (node_modules/nodemailer/lib/smtp-connection/index.js:968:22)
at SMTPConnection._processResponse (node_modules/nodemailer/lib/smtp-connection/index.js:764:20)
at SMTPConnection._onData (node_modules/nodemailer/lib/smtp-connection/index.js:570:14)
I was using the react-native default test case (see below) when Cannot log after tests are done happened.
it('renders correctly', () => {
renderer.create(<App />);
});
Apparently, the problem was that the test ended but logging was still needed. So I tried to make the callback in the test case async, hoping that the test won't terminate immediately:
it('renders correctly', async () => {
renderer.create(<App />);
});
And it worked. However, I have very little clue what the inner working is.
If you are using async/await type in your code, then this error can occur when you are calling async function without await keyword.
In my case, I have defined a function like this below,
async getStatistics(headers) {
....
....
return response;
}
But I have called this method like getStatistics(headers) instead of await getStatistics(headers).
When I included await, it worked fine and the issue resolved.
In my case while using nodejs + jest + supertest the problem was that when I import app from "./app" to my test file to do some stuff with supertest (request(app)), I actually import with app.listen() , because when I'm exporting app, export takes in account app.listen() too, but we don't need app.listen() in tests and it throws an error
"Cannot log after tests are done.Did you forget to wait for something async in your test?"
Here is all in one file(that's the problem!)
const app = express();
app.use(express.json());
// ROUTES
app.get("/api", (req, res) => {
res.json({ message: "Welcome to Blog API!" });
});
app.use("/api/users", usersRoutes);
app.use("/api/blogs", blogsRouter);
// The server will start only if the connection to database is established
mongoose
.connect(process.env.MONGO_URI!)
.then(() => {
console.log("MongoDB est connecté");
const port = process.env.PORT || 4000;
app.listen(port, () => console.log(`The server is running on port: ${port}`));
})
.catch(err => {
console.log(err);
});
export default app;
To solve this issue I created 2 separate folders:
// 1) app.ts
Where I put all stuff for my const app = express(), routes etc and export app
dotenv.config();
const app = express();
app.use(express.json());
// ROUTES
app.get("/api", (req, res) => {
res.json({ message: "Welcome to Blog API!" });
});
app.use("/api/users", usersRoutes);
app.use("/api/blogs", blogsRouter);
export default app;
// 2) index.ts
Where I put app.listen() and mongoose.connection() and import app
*import mongoose from "mongoose";
import app from "./app";
// The server will start only if the connection to database is established
mongoose
.connect(process.env.MONGO_URI!)
.then(() => {
console.log("MongoDB est connecté");
const port = process.env.PORT || 4000;
app.listen(port, () => console.log(`The server is running on port: ${port}`));
})
.catch(err => {
console.log(err);
});*
For me I needed to add an await before the expect() call also to stop this error (and an async before the test() callback function).
Also caused and fixed Jest not detecting coverage on the lines in the code throwing the error!
test("expect error to be thrown for incorrect request", async () => {
await expect(
// ^ added this
async () => await getData("i-made-this-up")
).rejects.toThrow(
"[API] Not recognised: i-made-this-up"
);
});
getData() returns an Axios call and in this case an error is caught by catch and re-thrown.
const getData = async (id) => {
return await axios
.get(`https://api.com/some/path?id=${id}`)
.then((response) => response.data)
.catch((error) => {
if (error?.response?.data?.message) {
console.error(error) // Triggered the error
throw new Error("[API] " + error.response.data.message);
}
throw error;
});
};
This happened to me because I had an infinite loop while (true). In my case, I was able to add a method for setting the value of the loop based on user input, rather than defaulting to true.
In my case, the error was caused by asynchronous Redis connection still online. Just added afterall method to quit Redis and could see the log again.
Working on Typescript 4.4.2:
test("My Test", done => {
let redisUtil: RedisUtil = new RedisUtil();
let redisClient: Redis = redisUtil.redis_client();
done();
});
afterAll(() => {
redisClient.quit();
});
I solved it with the env variables:
if (process.env.NODE_ENV !== 'test') {
db.init().then(() => {
app.listen(PORT, () => {
console.log('API lista por el puerto ', PORT)
})
}).catch((err) => {
console.error(err)
process.exit(1)
})
} else {
module.export = app
}
I faced same warnings. However the fix is bit weird:
The jest unit test script import a function (which is not export from src/). After I added the export to the function to be tested. The error disappears.
I had a similar issue:
Cannot log after tests are done. Did you forget to wait for something async in your test?
Attempted to log "Warning: You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. ".
It was due to a missing static keyword. This code caused the issue:
class MyComponent extends React.Component<Props, State> {
propTypes = {
onDestroy: PropTypes.func,
}
}
It should have been:
class MyComponent extends React.Component<Props, State> {
static propTypes = {
onDestroy: PropTypes.func,
}
}

How to test Promise catch with Mocha

I'm trying to test the GET HTTP method from a requests module:
const get = (host, resource, options) => {
...
return new Promise((resolve, reject) => fetch(url, opts)
.then(response => {
if (response.status >= 400) {
reject({
message: `[API request error] response status: ${response.status}`,
status: response.status });
}
resolve(response.json());
})
.catch(error => reject(error)));
};
And here is how I tested the .then part:
it('Wrong request should return a 400 error ', (done) => {
let options = { <parameter>: <wrong value> };
let errorJsonResponse = {
message: '[API request error] response status: 400',
status: 400,
};
let result = {};
result = get(params.hosts.api, endPoints.PRODUCTS, options);
result
.then(function (data) {
should.fail();
done();
},
function (error) {
expect(error).to.not.be.null;
expect(error).to.not.be.undefined;
expect(error).to.be.json;
expect(error).to.be.jsonSchema(errorJsonResponse);
done();
}
);
});
However I didn't find a way to test the catch part (when it gives an error and the response status is not >= 400).
Any suggestions?
It would also help me solve the problem a simple example with another code that tests the catch part of a Promise.
I've ended up writing the following code in order to test the catch:
it('Should return an error with invalid protocol', (done) => {
const host = 'foo://<host>';
const errorMessage = 'only http(s) protocols are supported';
let result = {};
result = get(host, endPoints.PRODUCTS);
result
.then(
() => {
should.fail();
done();
},
(error) => {
expect(error).to.not.be.null;
expect(error).to.not.be.undefined;
expect(error.message).to.equal(errorMessage);
done();
}
);
});

Angular 2 observable error testing with jasmine

I want to test this function:
register(): void {
let user: User = new User();
user.username = this.username.value;
user.email = this.email.value;
user.password = this.password.value;
this._authService.register(user)
.map(rsp => rsp.json())
.subscribe((response) => { //
this._router.parent.navigate(["Login"]); //
}, (error) => {
this.responseError = JSON.parse(error._body).message;
}, () => {
this._authService.login(user)
.map(rsp => rsp.json())
.subscribe((data: any) => { //
this._authService.handleSuccessLogin(data, user);
this._router.parent.navigate(["../Game"]);
});
});
}
My _authService using http but I want to fake that call. I have tried to call through in it and mocking the http, but even if my response was 4xx it ran on the success part. Is it possible to test the error part somehow?
To simulate an error, you need to use the mockError method of the MockConnection. It accepts an Error object as parameter not a Response one. To be able to provide hints like status code, you could extend the Error class like that:
class ResponseError extends Error {
status: number;
(...)
}
and use it this way:
it('Should return something', inject([XHRBackend, HttpService, Injector], (mockBackend, httpService, injector) => {
mockBackend.connections.subscribe(
(connection: MockConnection) => {
if (connection.request.url === 'file1.json') {
var err = new ResponseError();
err.status = 404;
connection.mockError(err);
(...)
In this case, an error is thrown in your data flow and gotten for example into the second callback specified in the subcribe method.