0

I am trying to mock an method of an object from rss-parser library. I have a class and a method inside using rss-parser object. But I got error below, did I do anything wrong? parseURL does exist in the object.

const RSSParser = require('rss-parser');
class MyClass {
    public my_method (RSS_URL) {
        const parser = new RSSParser();
        const data = await parser.parseURL(RSS_URL);
        return data;
    }
}

In my mock file:

import MyClass from '..'
const RSSParser = require('rss-parser');

describle ('test', () => {
    const myClass = new MyClass();
    const parser = new RSSParser();
    spyOn(parser, 'parseURL').and.callFake((_url) => {
        return 'data';
    });
})

Error:

Message:
    Error: <spyOn> : parseURL() method does not exist
    Usage: spyOn(<object>, <methodName>)
bunny
  • 1,797
  • 8
  • 29
  • 58

1 Answers1

0

You need to spy on the prototype, since that is what is actually being called.

Here is a similar issue:

Jasmine - how to spyOn instance methods

Edit for clarity

The spyOn function needs to be called on the prototype of the object instance, not the prototype of the class.

In this case, that would look something like:

const parser = new RSSParser()
const spy = spyOn(parser.prototype, 'parseURL').and.returnValue(new Promise(...))
Charles Desbiens
  • 879
  • 6
  • 14
  • I tried: spyOn(RSSParser.prototype, 'parseURL').and.callFake((_url) => { return 'data'; }); But still get Error: : parseURL() method does not exist. In this way, I did not create an object of RSSParser, but use the class directly. – bunny Aug 21 '20 at 02:51
  • you need to call the prototype of the object you created, not the base class. So `spyOn(parser.prototype, 'parseURL')` – Charles Desbiens Aug 21 '20 at 02:54
  • I updated it to the above, but it gives another error: Error: : could not find an object to spy upon for parseURL() – bunny Aug 21 '20 at 03:31
  • that's my mistake. Await shouldn't be in there. – Charles Desbiens Aug 21 '20 at 03:35
  • I updated my code to spyOn(parser.prototype, 'parseURL').and.returnValue(new Promise((resolve) => resolve('data'))); but it still gives me error: Error: : could not find an object to spy upon for parseURL().Am I doing anything wrong? – bunny Aug 21 '20 at 03:52