r/backtickbot • • Jul 22 '21

https://np.reddit.com/r/learnprogramming/comments/op0gwv/i_did_it/h65w5k8/

With something like the packages I mentioned. I'm going to quote the Jest docs here to show you what this would look like. It's in javascript, but the idea will apply to other languages.

So lets say I have a file called sum.js and in it I have some code:

function sum(a, b) {
  return a + b;
}
module.exports = sum;

This is fairly straight forward. I define a function sum and then I export this as a module, so I can import it and run it somewhere else. This is my unit and the function I want to test.

Now let's write a test for this function. I'll create a file called sum.test.js so Jest knows it is looking to test the sum.js file.

const sum = require('./sum');

test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});

This code makes up my test. First I import the code from sum.js using require() and I write my test. I give it a description then the function I am passing in runs the test. I give it the test case in expect() and I use .toBe() to say what I should get out of this function.

Now when I run my sum.test.js file, it will go through all the testcases in the file and tell me if they all give me what I would expect them to be or if some of the tests fail. This way, I can run my automated tests as much as I want so as I add new functionality, I can check all of my old tests still work.

If you don't like Jest there are other testing tools that do the same thing for javascript, or if you use a different language there will be tools that work for that. Your idea is the same though.

1 Upvotes

0 comments sorted by