Jest Flashcards
How to install jest
npm i jest
What should we name test files?
someName.test.js
How to write a basic test?
const ct = require(“../src/math”);
test(“should calcuate the tip amount”, ()=>{
const amount = ct(100,.1) expect(amount).toBe(10) });
How to write tests for async code?
test("Should work with async code", (done)=>{ setTimeout(()=>{ expect(1).toBe(2) done() },5000) });
or
test("Should work with async code", async ()=>{ await setTimeout(()=>{ expect(1).toBe(2) done() },5000) });
How to configure jest in the package.json file?
{ "name": "taskmanager", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "start": "node src/index.js", "dev": "env-cmd -f ./config/dev.env nodemon src/index.js", "test": "env-cmd -f ./config/test.env jest --watch" }, "jest": { "testEnvironment": "node" },
When testing a node application, why do we need to set the testEnvorionment to “node”
Because the defoult is “jsdom” which is a browser environment
How to test api or http requests using jest and super test
- install supertest
- Copy the entire index.js file over into a new file that lives in the same folder, then delete the port and .listen function and export that file.
- import the file to index.js and delete everything except for the port and .listen function.
- in the test folder create the .test.js file
- import the app.js file, import the supertest as request
- Setup the test using request like follows
const request = require('supertest'); const server = require("../src/app");
test(‘Should create a new user’, async()=>{
await request(server).post('/users').send({ name:'Andre', email:'andre@mail.com', password:"1234abcd" }).expect(201)
});
How to setup functions that need to run before each test?
beforeEach(async ()=>{ await User.deleteMany(); await new User(userOne).save() });
How to create mocks?
in the test directory create a __mocks__ folder.
Then create a folder inside of the __mocks__ folder with the name of the module or function to be mocked
inside that folder create the file and export a module containing the functions or calls to be mocked.
Which folder should be used to upload images during tests?
fixtures
What is the fixtures folder used for?
For images, files and other assests used during tests. Also for setups, like setting up databases before tests etc.