DEV Community

Cover image for Introduction to unit testing in JS

Introduction to unit testing in JS

Arek Nawo on February 03, 2019

This post is taken from my blog so be sure to check it out for more up-to-date content 😉 If you're new to programming or you're just a hobby progr...
Collapse
 
eljayadobe profile image
Eljay-Adobe • Edited

Cucumber uses Gherkin as its BDD language.

I think Gherkin does a good job, because BDD scenarios should be written by the product owner, and the goal of them is to represent both a formal requirement and an acceptance test in the given-when-then structure. Most product owners are not programmers, so having a BDD language expressed as some form of "embedded domain specific language" is an enormous barrier to entry.

Note: Gherkin isn't "free". The developers still need to create the infrastructure layer to support the nouns, verbs, and query the results of the actions which Gherkin depends upon.

I've seen BDD go awry because instead of being used by the product owner, they are (ab)used by the quality engineers to drive system tests or integration tests, or the software engineers to be (ab)used to express unit tests.

Whereas, TDD unit tests are not written by product owners, they are written by developers. They are not reflective of formal requirements, they are reflective of basic correctness. Their primary purpose it to design better code -- so they are written by developers as an aid for development, which puts strong pressure on the developer to leverage SOLID principles. A residual value is the byproduct of having a suite of unit tests to ensure basic correctness against regressions.

Using something like, say FitNesse, the full suite of requirements/acceptance tests take hours to run.

In contrast, a full suite of TDD-style unit tests should take second to run.

When a Gherkin test fails, one can say "uh oh, something in this general area is broken."

When a TDD-style unit test fails, one can say "the part of the code that does Xyz, in this exact Abc function, is broken". (Unless the test itself is broken, which sometimes happens.)

Collapse
 
gugadev profile image
Gustavo Garsaky

Good reading. I use Jest all time, except for Angular. Currently I'm building a UI library for a design system using Web Components (lit-element) but I don't have experience testing this kind of components. Any suggestion? Thanks.

Collapse
 
areknawo profile image
Arek Nawo

For this special use case, I think Mocha will be the best choice. Mainly because of its flexibility and extendability. Also, maybe this can be helpful. 😀

Collapse
 
gugadev profile image
Gustavo Garsaky

Yeah. I ended up with Karma and Mocha. Thanks!

Collapse
 
mfaghfoory profile image
Meysam Faghfouri

great and useful article. thanks