简体   繁体   中英

How do I test javascript (Jasmine) in this case?

Here is a modified shorter version of what I am trying to test.


    var Service = (function() {

      function doStuff(command, package) {
        var response = ""

        switch(command) {
          case "A":
            response = a(package);
            break;
          case "B":
            response = b(package);
            break;
          case "C":
            response = c(package);
            break;
          default:
            // should never get here
            response = "NOPE!";
        }

        return response;
      }

      function a(package) {
            // do stuff
      }

      function b(package) {
            // do stuff
      }

      function c(package) {
        // do stuff;
      }

      return {
        doStuff: doStuff,
        a: a,
        b: b,
        c: c
      }
    });

    module.exports = Service;

So basically, I am trying to write a unit test to test out the doStuff method, but when it hits each case, I just want to do something like spy on the methods like a, b, or c, instead of checking out the return values, because each of those functions a, b, and c either return true or false. So instead of just testing against true or false, I want to be sure the correct case is his.

I am having trouble figuring out a way to do this with the way it's currently coded. My test file for this class is creating a new instance of this, and I tried spying on the methods, but that did not work because they aren't called on the actual instance in this code, they are called locally. Is it possible with spies to do this? And if not, what is the recommended way to test in this manner?

Doesn't this work?

 var service = new Service(); const aSpy = spyOn(service, 'a').and.returnValue(true); // setup the routing they way you want it service.command = "A"; var res = service.doStuff(someTestPackage); expect(aSpy).toHaveBeenCalledWith(someTestPackage); expect(res).toBeTruthy(); 

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