你们能帮我在下面的这段代码中用茉莉花写测试用例吗

时间:2020-04-23 19:30:14

标签: javascript angularjs jasmine karma-jasmine

这里有两个数组,我需要从另一个数组中将对象插入数组。 下面是我的代码

scope.newBal=[];
scope.actualBal=[
{date:2020-02-04,
bal:100.0},
{date:2020-02-09,
bal:530.0},
{date:2020-02-16,
bal:190.0},
{date:2020-02-23,
bal:4560.0}];

scope.newBal=scope.actualBal.filter(b => b.date.isAfter(startDate));

In the above code I had stored the objects in *newBal* array, after the startDate from *actualBal* array. 
So in my *newBal* array I've the below data:-
scope.newBal=[{date:2020-02-16, bal:190.0}, {date:2020-02-23, bal:4560.0}];

But i'm unable to write the test cases of above code in jasmine, So can you guys help me in this.


1 个答案:

答案 0 :(得分:1)

首先在茉莉花中为上述代码编写单元测试用例,首先将所有与虚数据关联的初始化变量

  • startDate,带有任何特定日期。
  • scope.newBal作为空数组
  • scope.actualBal数组,其中包含两个对象,一个对象的日期早于startDate,另一个对象的日期早于startDate

然后调用上面代码封装的函数。 之后,您可以进行以下声明

  • scope.newBal数组具有一个元素,该元素是日期为startDate的对象。
  • scope.actualBal尚未更改,与之前初始化的相同。

以下是实现上述步骤的代码段-

it('scope.myFunction() should copy all objects from scope.actualBal post startDate to scope.newBal', function() {
  // setup - initialise scope variables
  scope.startDate = new Date(2020, 03, 26); // year, 0-indexed month, date;
  scope.newBal = [];
  var balance_prior_date = {date:new Date(2020, 03, 25), bal:100.0};
  var balance_post_date = {date:new Date(2020, 03, 27), bal: 50.0};
  scope.actualBal = [balance_prior_date, balance_post_date];

  // action - call encapsulating function
  scope.myFunction();

  // assert
  // only relevant object shall be copied to newBal array
  expect(scope.newBal.length).toBe(1);
  expect(scope.newBal).toContain(balance_post_date);
  // actualBal array should remain as it is
  expect(scope.actualBal.length).toBe(2);
})
相关问题