最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jest: how to test multiple functions in one file? - Stack Overflow

programmeradmin0浏览0评论

is there a way to test multiple functions in one file with jest?

in ch03.js:

var min = function(a, b) {
  if(a < b)
    return a
  else
    return b
}

// even/odd number checker

var isEven = function(number) {
  n = Math.abs(number);
  if (n==0)
    return true;
  else if (n==1)
    return false;
  else {
    return isEven(n-2);
  }
}

module.exports = isEven;

and my test file: in test/ch03-test.js

jest.dontMock('../ch03');

describe('min', function() {
  it('returns the minimum of two numbers', function() {
    var min = require('../ch03');
    expect(min(2, 3)).toBe(2);
    expect(min(22, 3)).toBe(3);
    expect(min(2, -3)).toBe(-3);
  });
});

describe('isEven', function() {
  it('checks if given number is even', function() {
    var isEven = require('../ch03');
    expect(isEven(0)).toBe(true);
    expect(isEven(-2)).toBe(true);
    expect(isEven(0)).toBe(true);
    expect(isEven(3)).toBe(false);
  });
});

I don't want separate files for every small javascript function. Is there a way to test multiple functions in one file?

is there a way to test multiple functions in one file with jest?

in ch03.js:

var min = function(a, b) {
  if(a < b)
    return a
  else
    return b
}

// even/odd number checker

var isEven = function(number) {
  n = Math.abs(number);
  if (n==0)
    return true;
  else if (n==1)
    return false;
  else {
    return isEven(n-2);
  }
}

module.exports = isEven;

and my test file: in test/ch03-test.js

jest.dontMock('../ch03');

describe('min', function() {
  it('returns the minimum of two numbers', function() {
    var min = require('../ch03');
    expect(min(2, 3)).toBe(2);
    expect(min(22, 3)).toBe(3);
    expect(min(2, -3)).toBe(-3);
  });
});

describe('isEven', function() {
  it('checks if given number is even', function() {
    var isEven = require('../ch03');
    expect(isEven(0)).toBe(true);
    expect(isEven(-2)).toBe(true);
    expect(isEven(0)).toBe(true);
    expect(isEven(3)).toBe(false);
  });
});

I don't want separate files for every small javascript function. Is there a way to test multiple functions in one file?

Share Improve this question asked Dec 3, 2015 at 13:01 StandardNerdStandardNerd 4,18310 gold badges48 silver badges79 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 5

You should try rewire

When "requiring" a module with rewire, it exposes getter and setter for variables in the module, including private ones.

Something like this should work:

jest.dontMock('../ch03');

var rewire = require('rewire');
var min = rewire('../ch03').__get__("min");

describe('min', function() {
  it('returns the minimum of two numbers', function() {
    expect(min(2, 3)).toBe(2);
    expect(min(22, 3)).toBe(3);
    expect(min(2, -3)).toBe(-3);
  });
});
发布评论

评论列表(0)

  1. 暂无评论