【问题标题】:TypeError: undefined is not a constructor in jasmine unit test with angularjsTypeError: undefined is not a constructor in jasmine unit test with angularjs
【发布时间】:2019-10-23 05:26:39
【问题描述】:

我在 Jesmine 测试中出现上述错误。代码有一个控制器,它调用 AppsService 服务来接收一系列应用程序的承诺响应,然后是 onLoad 方法 -

AppsService.initAndGetApps(appCredentialType)
        .then(onLoad)
        .catch(onError);

代码运行良好,但单元测试出错 -

TypeError: undefined is not a constructor(评估 'AppsService.initAndGetApps(appCredentialType).then(onLoad)')

我尝试在我的规范文件中使用 Jasmine 模拟 initAndGetApps 以及像这样的自定义方法(两者都给出相同的上述错误)-

1.

initAndGetApps : jasmine.createSpy("initAndGetApps").and.callFake(function (credentialType) {
    return [];  // empty is ok
}

2。

AppsService = {
    initAndGetApps: function (credentialType) {
        return []; 
    }
}

$provide.value('AppsService', AppsService);

AppsService 使用 deferred.promise 在根据 credentialType 参数进行一些计算后返回 Promise 响应(它也进行两次 Promise 调用)。测试无法调用 initAndGetApps,因为在 initAndGetApps 的第一行没有获取 credentialType 的控制台。

有人可以指导我模拟 AppsService 的正确方法吗?

【问题讨论】:

    标签: angularjs unit-testing promise jasmine mocking


    【解决方案1】:

    你没有在这两个模拟中返回一个承诺。如果有这些方面的内容,我会尝试:

    initAndGetApps : jasmine.createSpy("initAndGetApps").and.returnValue(
      new Promise(function(resolve, reject) {
        // not taking our time to do the job
        resolve(desiredReturnValue);
      }
    );
    

    您可以将返回值更改为模拟值,以便您的代码正常工作。

    【讨论】:

      猜你喜欢
      • 2015-09-18
      • 2019-07-15
      • 2022-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-14
      • 1970-01-01
      相关资源
      最近更新 更多