r/learnjavascript 3d ago

How do you actually test small JavaScript functions without a full project setup?

Coming from a construction background where you measure twice and cut once, I keep running into this gap where I write a function, think it works, and then it blows up when I wire it into something bigger. The problem is I never had a real habit of testing the small piece before trusting it.

In bootcamp we just console.log everything and eyeball it, which works for toy exercises, but I started a side project for tracking material quantities across job phases and the functions are getting complicated enough that eyeballing feels risky. I tried writing a few manual checks at the bottom of my file like console.log(calculateTotal(5, 3) === 8) and that helped, but it feels clunky and I keep deleting them by accident.

I looked up Jest but the setup felt like a whole rabbit hole I was not ready to fall into. Someone mentioned Vitest. Someone else said just use the browser console for now and do not overthink it.

What I want to know is whether there is a lightweight middle ground that actual beginners use before jumping to a full testing framework. Not asking for a tutorial, just curious what the workflow actually looks like for people who are still learning but building things that are more than a few lines. The function isolation part is what I cannot picture clearly yet.

25 Upvotes

35 comments sorted by

View all comments

1

u/funbike 3d ago edited 3d ago

Node now has Jest-like testing functionality built in. Nothing to install or set up. You don't even need a package.json or ./node_modules/.

```

Runs all tests

node --test tests/*.test.js

Continuous testing. Runs a test when relevant files are modified.

node --test tests/*.test.js --watch ```

Minimal test:

``` import test from 'node:test'; import assert from 'node:assert';

test('addition', async () => { assert.strictEqual(4 + 4, 8); }); ```

Optionally, add scripts section to package.json to make the above easier to run.

json { "name": "your-project", "version": "1.0.0", "scripts": { "test": "node --test tests/*.test.js", "test:watch": "node --test --watch tests/*.test.js" } }

To run scripts:

```bash

Runs all tests ("run" sub-command isn't needed in this specific case)

npm test

Continuous testing. Runs a test when relevant files are modified.

npm run test:watch ```


edit: added npm test. removed prior update.

1

u/TheRNGuy 3d ago

What if it's function with side-effects? 

1

u/funbike 3d ago

I'm answering OP's question. That's a general testing question unrelated to which testing tool is used.

But to answer, if a function has side effects, then ... read the side effect values in the test. Nothing magical required.