Quick Links:
expect
and typescript setup:mkdir my-jest-app; cd my-jest-app; npm init -y; mkdir __tests__ && echo "test('simple', () => expect(1).toBe(1))" > __tests__/a.ts && npm i -D expect jest @types/jest
package.json
file: "test": "jest --watchAll"
npm run test
IMPORTANT: For typescript support: docs, you need to install deps: npm i -D ts-jest @babel/preset-env @babel/preset-typescript
and create a file in root project i.e, babel.config.js
with below contents:
module.exports = {
presets: [
['@babel/preset-env', {targets: {node: 'current'}}],
'@babel/preset-typescript',
],
};
Check this issue on jest’s github: Click here
.toEqual
My Luxon Notes: Learn Luxon: Click here
// For services:
expect(...).toEqual({
_id: expect.any(mongoose.Types.ObjectId),
createdAt: expect.any(Date),
updatedAt: expect.any(Date),
})
// For e2e:
expect(...).toEqual({
_id: expect.stringMatching(SIMPLE_MONGODB_ID_REGEX),
createdAt: expect.any(String),
updatedAt: expect.any(String),
startDate: '2022-10-24T00:00:00.000Z', // using dates with `luxon.DateTime.fromISO('2022-10-17T00:00:00Z').toJSDate().toISOString()`
endDate: '2022-10-25T23:59:59.000Z', // using dates with `luxon.DateTime.fromISO('2022-10-25T23:59:59Z').toJSDate().toISOString()`
// NOTE the difference of extra .000 before Z
})
it.only('if given path is exists then it will return that same path', async () => {
function runTest() {
const tempFilePath = path.join(os.tmpdir(), 'myfile.jpg');
const fh = fs.openSync(tempFilePath, 'w');
fs.writeSync(fh, '.', 3);
fs.closeSync(fh);
expect(existsSync(tempFilePath)).toBe(true);
unlinkSync(tempFilePath);
expect(existsSync(tempFilePath)).toBe(false);
}
for (let i = 0; i < 10_000; i += 1) {
console.log('iter:', i);
runTest();
}
});
Source: Click here
Source: Click here
Source (Jest Docs): Click here
const myMockFn = jest
.fn(() => 'default')
.mockImplementationOnce(() => 'first call')
.mockImplementationOnce(() => 'second call');
console.log(myMockFn(), myMockFn(), myMockFn(), myMockFn());
// > 'first call', 'second call', 'default', 'default'
jest.spyOn(..., ...).mockImplementation(() => Promise.resolve(undefined))
along with toHaveBeenCalledWith
assertions(check: Why use mock testing functions
in telegram slasher-private-channel to know specifics learned)
Medium Article suggested by Eric’s Suggested Article: Click here
expect().toEqual(...)
Tip: If you don’t have string matches you can use store sample date in .json
file as well.
const SIMPLE_MONGODB_ID_REGEX = /^[a-f\d]{24}$/i // 24 characters ~Sahil
const response = [
{
_id: '63ab12b2fa6c5356d22a298d',
userName: 'yolo',
firstName: 'Nelson Mandela',
profilePic: 'http://localhost:4444/placeholders/default_user_icon.png',
},
]
// Learn Usage of:
// 1. .toEqual(...)
// 2. expect.stringMatching(...)
// 3. expect.not.stringContaining(...)
expect(response).toEqual([
{
_id: expect.stringMatching(SIMPLE_MONGODB_ID_REGEX),
userName: 'yolo',
firstName: 'Nelson Mandela',
profilePic: 'http://localhost:4444/placeholders/default_user_icon.png',
},
])
expect([{name: 'sahil rajput'}]).toEqual([
{
name: expect.stringContaining('sahil'),
},
])
expect([{name: 'sahil rajput'}]).toEqual([
{
name: expect.stringContaining('rajput'),
},
])
expect([{name: 'sahil rajput'}]).toEqual([
{
name: expect.not.stringContaining('om'),
},
])
```
describe.only('something', () => {
it.only('shoudl it be?', (done) => {
console.log('hello');
done() // if done is not called then the test will not pass at all. In fact the setTimeout warning is thrown.
});
});
Click here: Official Docs - Click here
node --inspect-brk node_modules/.bin/jest --runInBand [any other arguments here]
it('does a lot of stuff exceeding default 5 sec timeout', async () => {
// ...
}, 10000)