DEV Community

Williams Oluwafemi
Williams Oluwafemi

Posted on

Automated Testing - is it really worth it?

'one of the challenges of being a software engineer is proving that your code works'

-Unknown

Well I buy into this, many times I find myself in a situation where I believe I just created a masterpiece, where everything functions properly (or at least makes me think it does) only for me to run into some serious logic errors. So what's the solution to this dilemma? Automated Testing?

Automated testing is writing a bunch of test suites to assert whether your piece of code is functioning as desired. A very popular testing framework I also work with is Mocha, which allows your import assertions styles whether BDD or TDD, it's so convenient because the syntax is near natural language, a popular assertion library to use hands in hand with Mocha is Chai which gives you the flexibilty of using multiple assertion styles.

Consider the following

So you want to create a function that accepts a card number and returns a the name of the card ie
detectNetwork('12365478635') should return either mastercard or visa depending on the first 3 characters or the length

detectNetwork = function (cardNumber) {
if(cardNumber.startaWith('31') && cardNumber.length == 16)
return 'Visa'
}

Creating this function is relatively easy, but how do you test it? Manually console log the function with the card number argument? Good idea, but what happens when you have numbers going into thousands? Console log them too? Probably not. That's where automated testing comes in

Simply write your test suites using for loops for larger numbers and voila, life is easy again, some thing as simple as

//TDD
const expect = chai.expect

describe('Visa', function() {

it('should return Visa for cardNumber with prefix 31 and length of 16', function() {
expect(detectNetwork('3143688426790').toEquals('Visa')
}

}

//BDD
const should = chai.should(()

describe('Visa', function() {

it('should return Visa for cardNumber with prefix 31 and length of 16', function() {
(detectNetwork('3143688426790').should.equals('Visa')
}

}

Another beat trick to get compiling your test cards is to store them in an array and call them with the test suite using a for loop.

You can get started with the Mocha and Chai with the links below

http://mochajs.com/

https://www.chaijs.com/

Top comments (0)