javascript - 编写 JavaScript 测试来测试其他函数的调用,而不实际调用它们

标签 javascript angularjs unit-testing jasmine karma-runner

我的任务是为另一个团队编写的一些 AngularJS 代码编写单元测试,但他们没有编写任何测试

他们编写了以下函数,但我不知道如何测试它

function showCallAlerts(callRecord, isInEditMode, callBack) {
    var callAlerts = populateCallAlertOnEditCall(callRecord.callAlert);
    var callModalInstance = openAlertModalInstance('Call', callAlerts, callBack);
    if (callModalInstance !== undefined && callModalInstance !== null) {
    callModalInstance.result.then(function() {
        // Show equipment alerts based on company details
        showEquipmentAlertsBasedOnCompanyDetails(callRecord, isInEditMode, callBack);
    });
    } else {
    // Show equipment alerts based on company details
    showEquipmentAlertsBasedOnCompanyDetails(callRecord, isInEditMode, callBack);
    }
}

我需要测试每个函数是否被调用,而不用担心它们的作用,因为我将单独测试它们,只关心它们被调用。

当调用 populateCallAlertOnEditCall 时,它需要返回一个空数组或一个包含某些项目的数组

当调用 openAlertModalInstance 时,它​​需要返回 undefined 或传递给 showEquipmentAlertsBasedOnCompanyDetails 的内容

showEquipmentAlertsBasedOnCompanyDetails 实际上应该被调用,我将单独测试该方法,只是它被调用了

我已经设法编写代码来测试简单的功能,但没有像这样的代码,所以任何帮助将不胜感激,我今天下午的大部分时间都在试图弄清楚

最佳答案

您可以使用 jasmine 来模拟您不感兴趣测试的函数调用。例如,您可以告诉 jasmine 每次调用“populateCallAlertOnEditCall”时返回一个空数组。我将写一个示例,可能会让您有所了解:

describe('My Test Spec', function() {
   var myController;

   ...

   beforeEach( inject(($controller) => {
        myController = $controller("myControllerName");
   }));

  it('Testing showCallAlerts when populateCallAlertOnEditCall returns an empty array', inject(function($controller) {
        //setup
        //this will replace every call to populateCallAlertOnEditCall with
        //the function inside callFake
        spyOn(myController, 'populateCallAlertOnEditCall ').and.callFake(function() {
              return []; //returning an empty array.
        });

        //action
        myController.showCallAlerts(...);

        //assert
        //Do your checking here.
  }));

  it('Testing showCallAlerts when populateCallAlertOnEditCall returns a non-empty array', inject(function($controller) {
        //setup
        //this will replace every call to populateCallAlertOnEditCall with
        //the function inside callFake
        spyOn(myController, 'populateCallAlertOnEditCall ').and.callFake(function() {
              return [1,2,3,4]; //returning a non-empty array.
        });

        //action
        myController.showCallAlerts(...);

        //assert
        //Do your checking here.
  }));

 });

关于javascript - 编写 JavaScript 测试来测试其他函数的调用,而不实际调用它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39394089/

相关文章:

java - 适合单元测试的类的一般结构

javascript - 添加到数组 jQuery

javascript - Kendo ui - 在 child 添加/编辑时获取父网格项目(网格层次结构)

javascript - AngularJS 等待 $http 请求

.net - Visual Studio 中 NUnit 属性 [SetUp()] 的对应物

c# - Moq.CaSTLeProxyFactory' 无法加载文件或程序集 'CaSTLe.Core

php - Ajax 在同一页面上发布到 php 不起作用

javascript - 自然排序数组数组

javascript - 获取复选框组 Angular 1.6 的选定值

javascript - 日期选择器弹出窗口不起作用