JavaScript Cheat Sheet Summary for Test Automation
1. Variable Declarations
let, const, var: Use const for constants, let for block-scoped variables in tests.
const username = "admin";
2. Functions & Arrow Functions
Arrow functions are concise and widely used in test steps.
const login = () = { ... };
3. Conditional Statements
Use if / else to control flow based on test conditions or API responses.
4. Loops & Arrays
for, forEach, map, filter help loop through test data.
users.forEach(u = expect(u).to.have.property('id'));
5. Async Handling
async/await and Promise.then() handle asynchronous test steps like UI interactions or API calls.
await page.click('#login');
6. Error Handling
Wrap flaky test steps in try/catch to prevent test crashes.
try { await page.click(...); } catch (e) { ... }
7. Test Definitions
describe and it define test suites and test cases (Mocha, Jasmine).
describe('Login Suite', () = { it('should login', () ={ ... }) });
8. Assertions
Use expect() or assert() (from Chai or built-in tools).
expect(status).to.equal(200);
9. DOM & UI Selectors
Native: document.querySelector()
Cypress: cy.get('#btn')
Playwright: page.locator('text=Submit')
10. JSON & Objects
Handle API responses with JSON.parse(), destructuring, and object methods.
const { name } = JSON.parse(res.body);
11. Strings & Arrays
Use .includes(), .startsWith(), .map() etc., in validations.
expect(url.includes('dashboard')).to.be.true;
12. Storage
Test session/localStorage for auth/state.
localStorage.setItem('token', 'abc');
13. Miscellaneous
console.log() for debugging.
Math.random() to generate dynamic test data.
Object.keys() / Array.isArray() for dynamic structure checks.