简体   繁体   English

包括外部API时如何测试AngularJS?

[英]How to test AngularJS when including external APIs?

I'm using the SoundCloud JavaScript SDK with AngularJS, and trying to run Karma tests on it. 我正在将SoundCloud JavaScript SDK与AngularJS结合使用,并尝试在其上运行Karma测试。 I keep getting the error Error: [$injector:modulerr] Failed to instantiate module SoundcloudApp due to: ReferenceError: Can't find variable: SC when I run the tests. 我不断收到错误Error: [$injector:modulerr] Failed to instantiate module SoundcloudApp due to: ReferenceError: Can't find variable: SC运行测试时Error: [$injector:modulerr] Failed to instantiate module SoundcloudApp due to: ReferenceError: Can't find variable: SC

The variable SC (provided by the SoundCloud API, when including the script) is used in an AngularJS service: 变量SC(包括脚本时由SoundCloud API提供)在AngularJS服务中使用:

angular.module('SoundcloudApp').provider('SoundCloud', function() {
  SC.initialize({
    clientId: 'SeES8KzD8c44J9IU8djbVg'
  });

  this.$get = function($q) {
    return {
      getUser: function(id) {
        // returns user object with a given id

        var user = $q.defer(); 


        SC.get('/users/' + id, function (userData, err) {
          if (err) {
            user.reject(err.message);
          } else {
            user.resolve(userData);
          }
        });

        return user.promise;
      }
    };
  };
});

Should I just mock this service? 我应该嘲笑这项服务吗? How do I do that? 我怎么做?

You can inject mocks into your service by using $provide. 您可以使用$ provide将模拟注入到您的服务中。

You can find an explanation in the answer to this question: Injecting a mock into an AngularJS service 您可以在以下问题的答案中找到解释: 将模拟注入AngularJS服务

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM