简体   繁体   中英

Unit Testing for EventEmitter with Jest

I'm new to unit testing as a whole and especially new with javascript. I'm working on some unit testing with Jest and I came across this one script that doesn't make much sense to me. But, I figured I'd try to write a test for it.

I am completely new to this so even learning about EventEmitter is throwing me off. I did read that you have to call, in this case, newCommandEmitter but this script doesn't have that at all. It's just three lines.

Code is below, but I want to know, is this even worth writing a test for?

const EventEmitter = require('events')
const newCommandEmitter = new EventEmitter()
module.exports = newCommandEmitter

My test script is as follows:

const newCommandEmitter = require("./newCommandEmitter.js");
const events = require("events");

jest.mock("./newCommandEmitter.js");
jest.mock("events")

describe("Testing for events if command is used for events.", () => {

    test("First test to see if we get events data.", async () => {

        expect(newCommandEmitter).toBeTruthy();
    });
});

Short answer: No, it is not worth it to unit test code like this.

Why?

  1. Time inefficiency - testing trivial execution paths/pieces of code (like the one you have given) gives us little to no benefits, but is very time expensive, because of how often such path/code appears. That is why we usually test everything that can possibly break. Over the top testing wastes precious time which can be used for writing functional code or writting tests where they are needed.

  2. Questioning the axioms of our programming language/framework - What you are doing here can be considered as such, because the only thing you do other than exporting/importing is creating an object with built in constructor. When using built in features we assume that they are working fine as they are and that they should never break (except for the cases specified in the docs). Otherwise to stay consistent we would need to question each and every function, class and operator given to us by the creators of the language/library. Unit tests shouldn't test the language in which the code is written, but the code itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM