无法让BeBalled()在Jade测试脚本中工作

时间:2016-05-08 03:17:22

标签: javascript tdd jestjs

我无法让toBeCalled()在我的Jade测试脚本中工作。

运行Jade测试时出现以下错误信息:

Error: toBeCalled() should be used on a mock function or a jasmine spy

我打电话给jest.unmock('../fooey')所以不确定我为什么会收到错误?

fooey.js

var foo = function(phrase) {
    return bar(phrase);
}

var bar = function(greeting) {
    console.log(greeting + " Watz up?");
}

foo("Hi Bob!");

module.exports.foo = foo;

module.exports.bar = bar;

fooey-test.js:

jest.unmock('../fooey'); // unmock to use the actual implementation.

describe('fooey()', () => {

   const foo = require('../fooey').foo;
   const bar = require('../fooey').bar;

   it('bar() is called.', () => {

      foo("Hi Bob!");

      expect(bar).toBeCalled();
   });
});

1 个答案:

答案 0 :(得分:0)

我使用了模拟bar()和使用spyOn()......

fooey.js

var Fooey = function() {
    // var self = this;

    this.foo = function(phrase) {
        // var result = self.bar(phrase);
        var result = this.bar(phrase);

        return result;
        // return "Junky."
    };

    this.bar = function(greeting) {
        var result = greeting + " Watz up?"

        console.log(result);

        return result;
    };
};


module.exports = Fooey;

fooey-test.js

jest.unmock('../fooey'); // unmock to use the actual implementation.

describe('fooey()', () => {

   const Fooey = require('../fooey');
   const fooey = new Fooey();

  it('mock: bar() is called.', () => {

      var myFooey = {
         foo: fooey.foo,
         bar: jest.genMockFunction()         
      };

      myFooey.foo("Hello");

      expect(myFooey.bar).toBeCalledWith("Hello");
   });

   it('bar() is called with "Hi Bob!".', () => {

      spyOn(fooey, 'bar');

      fooey.foo("Hi Bob!");

      expect(fooey.bar).toHaveBeenCalledWith("Hi Bob!");
   });
});