Anji
Anji

Reputation: 715

How to write unit testing for functions in React js?

I have a function in my App.js file as below.

function unCamelCase(val) {
   return val.replace(/([a-z])([A-Z])/g, '$1 $2')
        .replace(/\b([A-Z]+)([A-Z])([a-z])/, '$1 $2$3')
        .replace(/^./, function(str){ return str.toUpperCase();   })
}

How to write unit testing for the above function.

Thanks in Advance.

Upvotes: 2

Views: 2074

Answers (1)

Caleb Syring
Caleb Syring

Reputation: 1189

Have you ever heard of Jest? I believe Facebook uses it to test all their javascript code. I have used it to a very minor extent in one of my projects. If you're interested, this page explains how to get it set up.

https://jestjs.io/docs/en/getting-started.html

Example Implementation (with unCamelCase.js being outside of a test folder and test_unCamelCase.js being inside):

// test_unCamelCase.js

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

test("test unCamelCase", () => {
    expect(unCamelCase("camelCase")).toBe("Camel Case")
    expect(unCamelCase("moreThanTwoWords")).toBe("More Than Two Words")
    expect(unCamelCase("symb0lsAndNumber$")).toBe("Symb0ls And Number$")
})

// unCamelCase.js

function unCamelCase(val) {
    return val.replace(/([a-z])([A-Z])/g, '$1 $2')
         .replace(/\b([A-Z]+)([A-Z])([a-z])/, '$1 $2$3')
         .replace(/^./, function(str){ return str.toUpperCase();   })
}

module.exports = unCamelCase

Upvotes: 1

Related Questions