如何使用Jasmine模拟链式承诺?

时间:2017-10-20 00:54:15

标签: angularjs jasmine angular-promise

我正在为包含这段代码的方法编写单元测试:

"ecsTask":{
      "Properties":{
        # ... other stuffs
        "container_definitions": [
          {
            "name": {"Ref":"AWS::StackName"},
            "image": {"Ref":"DockerImage"},
            "portMappings": [
                # ... dynamic list of ports, example below
                {
                    "ContainerPort": "123",
                    "HostPort": "456"
                },
            ],
            "environment":{ "Ref": "EnvironmentVariables" },
          # ... other stuffs
          }
        ]
      },

Name.get($scope.nameId).then(function(name){ Return name; }).then(doSomething); 看起来像这样。

function doSomething(name)

我不需要测试这部分代码。既然我不能在我的测试中忽略它(或者我可以吗?),我需要嘲笑它。我嘲笑了第一个承诺

function doSomething(name){
    addNametoList(name);
}

并认为它会传播到第二个 spyOn(mockName, 'get').and.returnValues($q.resolve({"Mike"})); ,但then(doSomething)name中传播undefined

我想我也必须模仿addNametoList,但我不知道如何将它们连在一起。

2 个答案:

答案 0 :(得分:0)

  

我不需要测试这部分代码。因为我不能忽视   在我的测试中(或者我可以吗?),我需要嘲笑它。我嘲笑了第一个   许

IMO,没有必要对这些设置进行整体测试。 单独测试每个单元。

例如

A = () => {
  ...
}

B = () => {
  ...
}

C = () => {
  ...
}

现在我们有F,它叫A B& ç

F = () => A(B(C))

或者在你的情况下

F = () => A().then(B).then(C)

我们可以测试F,但它需要一些设置,并且很脆弱。 它更适合测试A,B和B C(给予适当的F覆盖)并忽略F。

答案 1 :(得分:0)

您的(部分)控制器代码

$scope.list = [];

function addNameToList(name) {
  $scope.list.push(name);
}

function doSomething(name){
  addNametoList(name);
}

$scope.functionToTest = function() {
  Name.get($scope.nameId).then(function(name){
    return name;
  }).then(doSomething);
};

您的测试

it('should add the name to the list when Name.get() is resolved', function() {
  // Arrange
  var getDeferred = $q.defer();
  spyOn(mockName, 'get').and.returnValue(getDeferred.promise);

  // Act
  $scope.functionToTest();
  getDeferred.resolve('some name that should be in the list');
  $scope.$apply();

  // Assert
  expect($scope.list).toEqual(['some name that should be in the list']);
});

<强>注释

请注意,代码的以下部分不会完成任何操作,并且可以在不影响任何内容的情况下删除。

.then(function(name){
  return name;
})