简体   繁体   中英

How to mock imported constants with Jest

I have a soap mapping method that I want to test. The soap calls need to be mocked but I can't figure how to do this.

This is the map method I want to test:

import LovSoapCaller from './lovSoapCaller';

const lovOptinSoap = new LovSoapCaller('getAllOptinTypes');

class ScrSoapMapping extends SoapWSMapping {
  map(args) {
    const customerNumber = +args.shift();
    const result = lovOptinSoap.callWS(customerNumber);
    return result.optinValue;
  }
}

The object I want to mock is lovOptinSoap so that it returns something without calling the soap web service. I found examples to mock an import but I think this is tricky because I don't really export an object in LovSoapCaller :

class LovSoapCaller extends SoapCaller {
  constructor(method) {
    super(URL, method, mapping);
  }

  callWS(lang) {
    const params = {
      language: lang,
    };
    return super.call(params);
  }
}

export default LovSoapCaller; 

I tried with Jest spyOn() 's method but I don't get how I can "inject" my mocked (or spied) object...

You can add a constructor ( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor ) to your class. You'll then be able to pass lovOptinSoap into that constructor.

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