简体   繁体   中英

Node js Unit test sinon chai

How to create unit test for the bellow file

index.ts

import ----
import ----

let workerService = new WorkerService();
let creatWorkerPromise = Promise.promisify(workerService.createWorkers);

creatWorkerPromise()
.then(function(){
    let kafkaService =  new KafkaService(kafkaConfig, workerService);
})
.catch(function (err: any) {
    console.log('Error while creating workers:', err);
});

It's kind of difficult to test something that is not a unit, as a unit usually exposes methods that are to be tested, so I am assuming that you do this eventually in the test code. So here goes:

 /////////// // index.js /////////// // stubs for this example to work var createWorkerPromise = function(){ return Promise.resolve(); } var workerService, kafkaConfig; function KafkaService(){ throw new Error("crashes test"); } function exportedFunction(){ return createWorkerPromise() .then(function(){ var kafkaService = new KafkaService(kafkaConfig, workerService); }) .catch(function (err) { console.log('Error while creating workers:', err); }); } /////////// // test.js /////////// var log = console.log.bind(console); var assert = function(expr) { if(!expr) throw new Error("AssertionError"); log("TEST OK"); } // the test var spy = sinon.spy(console, 'log'); exportedFunction().then(function test() { assert(spy.called); }).catch(log.bind(null, "TEST FAILED")) 
 <script src="https://unpkg.com/sinon@latest/pkg/sinon.js"></script> 

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