I am new to javascript and came across this problem. After searching for a solution on Google I realized that there is no such question asked on StackOverflow. After I figured out the solution I thought of sharing it here in case it helps someone.
I'm building a To-Do list app where a user is created with fields username (email), password, and DOB. I'm using MongoDB to store user and todo data. After the user is created, they can log into the app with their username and password.
When the user logs in, I need to get their userID from their username. The path I'm using to GET the userID is - /api/user/username/:username
I'm using Jest for TDD so I need to write tests first for the above case.
One of the specifications out of different test cases in the test suite is: get UserID from username and return userID in MongoDB ObjectID format.
How do I check whether the userID returned is in MongoDB ObjectID format?
To check if a userID is a valid MongoDB ObjectID using Jest, one can use
expect(ObjectID.isvalid(userID)).toBeTruthy();
One example is as follows:
it(`must get userID when username is in valid email format & available in db and return userID in mongoDB ObjectID format`, async (done) => {
const response = await request(app)
.get(`/api/user/username/${username}`)
.set({ "x-token-header": jwtToken })
.send();
const { body } = response;
expect(ObjectID.isValid(body)).toBeTruthy();
done();
});