简体   繁体   中英

Unit Testing with Jasmine - Can not spyOn mocked method

I am writing a javascript library that calls a method on another js lib. Most of the time i would create a mock function of the 3rd party library and spy on it. However, it doesn't seem to work.

For example:

mymain.js

export const checkForExternalFunc = () => {
  try {
   return com.externalFunc
  } catch (error) {
    return false
  }
}

mymain_spec.js

import { checkForExternalFunc } from './src';

describe('checkForExternalFunc', () => {
 let com = com || {};
 com.externalFunc = function () {
   return true;
 };

 it('return the function when com.externalFunc is present', () => {
  spyOn(com, "externalFunc");

  let check = checkForExternalFunc();
  expect(check).toBe(jasmine.Any(function));
 });
})

and this would give me an error

ReferenceError: com is not defined

Function in 3rd part library

var com = com || {};
com.externalFunc = function () {
   // return something
};

Any suggestion how i can approach this? Also i have researched a little on Stub with Sinon but not sure how to use it properly. Any help will be appreciated. Thanks!!

Note: I setup project with webpack + babel, karma, jasmine.

Thanks @AdityaBhave for pointing out. I only need to make sure my mock function and the actual one are actually the same. Please see comment above.

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