简体   繁体   中英

Stub a dependency function in sinon

I am using intern as testing framework and sinon for mocking the data. I dont want to hit the server for http requests during unit tests. So I have created a module that returns the data in deferred.promise as shown below:

define(["require", ..], function(require, ...) {
  function fakerequest(){
    dfd = new Deferred();
    setTimeout(function(){
      deferred.resolve(data);
    },100);
    return dfd.promise;
  }
  return fakerequest;
});

And this is the original AMD request module that hits an external server with http request:

define(["require", ..], function(require, ...) {
  function request(){
    dfd = new Deferred();
    ... 
    return dfd;
  }
  return request;
});

And this the module that I wanted to test. And it uses the request function for some data:

define(["require", ..], function(require, ...) {
  var QuerySomething = {
    execute: function(){
      ...
      return request();
    };
  }
  return QuerySomething;
});

Now I want to test the QuerySomething module but I dont want it to use the original request function but instead use the fakeRequest function. So in my intern test, I used sinon to stub the original request with the fake one.

registerSuite({
  name: 'QuerySomething',

  setup: function(){
    stub = sinon.stub(request, "request", fakeRequest);
  },

  teardown: function () {
    stub.restore();
  },

execute: function(){
  queryTask.execute(query).then(function(results){
    console.log(results);
  });
}

But I am getting this error:

TypeError: Attempted to wrap undefined property request as function

Can someone please let me know how to mock the dependency function?

Sinon can't directly stub a AMD dependency. When it stubs an object method, it's replacing the method on the object with a new method. Say you have an object foo with a method bar . bar is a property on foo . Your code calls foo.bar() at some point.

Now you stub the bar method. The property bar on foo is modified to point at a new function (the stub). When your code calls foo.bar() now, the stub is actually executed since foo.bar points at the stub instead of the original function.

The standard way to mock something like your request module with AMD is to use a loader map . With a loader map, you can configure your QuerySomething module to load the fake request module as a dependency rather than the real one during testing.

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