简体   繁体   中英

Mocha test case for variable assignment

I am new to mocha test cases. Please let me know how to write a test case for this:

Controller function:

var k, b = 10;

this.myFunction = function() {
  k = 'Test failed';
  if(b == 10){
    k = 'Test Passed';
  }
};

Test Case:

it('Should pass the test', function(){
  controller.myFunction();
  expect(k).to.equal('Test passed');
});

controller.myFunction() is called. But the value of k becomes undefined. Please help me fix this!

You should use rewire package to set or get the private variables defined in the module scope.

Eg

controller.js :

var k,
  b = 10;

const controller = {
  myFunction: function() {
    k = 'Test failed';
    if (b == 10) {
      k = 'Test Passed';
    }
  },
};

module.exports = controller;

controller.test.js :

const rewire = require('rewire');
const { expect } = require('chai');

describe('61384893', () => {
  it('should pass', () => {
    const controller = rewire('./controller');
    controller.myFunction();
    expect(controller.__get__('k')).to.be.equal('Test Passed');
  });

  it('should pass too', () => {
    const controller = rewire('./controller');
    controller.__set__('b', 1);
    controller.myFunction();
    expect(controller.__get__('k')).to.be.equal('Test failed');
  });
});

unit test results with 100% coverage:

  61384893
    ✓ should pass (45ms)
    ✓ should pass too


  2 passing (66ms)

---------------|---------|----------|---------|---------|-------------------
File           | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
---------------|---------|----------|---------|---------|-------------------
All files      |     100 |      100 |     100 |     100 |                   
 controller.js |     100 |      100 |     100 |     100 |                   
---------------|---------|----------|---------|---------|-------------------

source code: https://github.com/mrdulin/expressjs-research/tree/master/src/stackoverflow/61384893

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