如何更改$scope变量值并测试angularjs jasmine

如何更改$scope变量值并测试angularjs jasmine,angularjs,testing,jasmine,karma-runner,Angularjs,Testing,Jasmine,Karma Runner,我有第一种情况,产品id应该是未定义的 var $stateParamsStub = { scheduleId : undefined } 在我的控制器中,我正在检查isUpdate true或false。如果productId未定义,则表示isUpdate应为false,在另一种情况下,它应为true $scope.isUpdate = stateParams.scheduleId ? true : false; 我的测试文件 $injector.invoke(myControll

我有第一种情况,产品id应该是未定义的

var $stateParamsStub = {
    scheduleId : undefined
}
在我的控制器中,我正在检查isUpdate true或false。如果productId未定义,则表示isUpdate应为false,在另一种情况下,它应为true

$scope.isUpdate = stateParams.scheduleId ? true : false;
我的测试文件

$injector.invoke(myController, this, {
    $scope: $scope,
    $stateParams: $stateParamsStub    
});
我的第一个测试用例按预期工作,因为我在注入时将stateParams.scheduleId设置为undefined

it('should check update as false', function () {
    expect($scope.isUpdate).toBeFalsy();
});
我的案例2失败了

it('should check update as false', function () {
    $stateParamsStub = {
        productId: "86C07C05-41FB-41E9"
    }
    $scope.$digest();
    expect($scope.isUpdate).toBeTruthy();
});
第二种情况的输出:
预期false为truthy。


我知道在执行每个“it”之前,它正在设置我之前分配的默认值。如何为另一个测试更改该值?因此,它需要一个更新的值?

看起来您正在依赖引用,因此,您必须保存相同的引用

试试这样:

it('should check update as false', function () {
    $stateParamsStub.scheduleId = "86C07C05-41FB-41E9"; // <-- the change

    $scope.$digest();
    expect($scope.isUpdate).toBeTruthy();
});
it('should check update as false',function(){

$stateParamsStub.scheduleId=“86C07C05-41FB-41E9”//在控制器代码中,我可以看到您正在与scheduleId进行比较:

$scope.isUpdate = stateParams.scheduleId ? true : false;

但是在您的测试用例中,您正在JSON中设置productId。请将您的测试用例和控制器与JSON中的单个属性对齐,因为状态参数只能通过在beforeach节中执行的注入传递,因此我们无法修改它。 所以,我直接更新了控制器范围值

it('should check update as true', function () {
$scope.isUpdate=true // <-- the change
$scope.$digest();
expect($scope.isUpdate).toBeTruthy();

<-- did some other testing based on this condition -->
}
it('should check update as true',function(){

$scope.isUpdate=true//您正在检查
scheduleId
,但您在对象中有
productId
。这很奇怪!这是打字错误吗?很抱歉,这是我在此处发布问题时的错误,已修复。