0

Ahh! Why does node fooey.js work fine when run on the NodeJS command line, but fails when run from Jest/Jasmine?

Jest/Jasmine ERROR: it foo() returns a string. - TypeError: this.bar is not a function

If I use the commented out lines below for self = this and self.bar() the tests pass OK.

fooey.js

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

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

        return result;
    };

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

        console.log(result);

        return result;
    };
};


module.exports = Fooey;

var fooey = new Fooey();

fooey.foo("Hi Bob!");
fooey.bar("Yo Carl!");

fooey-test.js

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

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

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

   const foo = fooey.foo;
   const bar = fooey.bar;


   it('foo() returns a string.', () => {

      var result = foo("Hi Bob!");

      expect(typeof result).toBe('string');
   });
});
Giant Elk
  • 4,439
  • 9
  • 39
  • 54
  • The problem is precisely because of the difference in ***how you're calling `foo()`.*** Nothing specific to Jasmine. – deceze May 10 '16 at 01:55
  • @deceze Can you be more specific, I can't see what you see -) – Giant Elk May 10 '16 at 01:58
  • `fooey.foo()` !== `foo()`. Read the duplicate *how the `this` keyword works*. – deceze May 10 '16 at 02:00
  • OK, I got my Jest test working using `fooey.foo("Hi Bob!")` instead of `foo("Hi Bob!")`. Thanks, I'll read up more on `this`: http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work – Giant Elk May 10 '16 at 02:06

0 Answers0