我刚刚开始为我的AngularJS应用程序编写测试,并且正在Jasmine中进行测试。
以下是相关的代码段
ClientController:
'use strict';
adminConsoleApp.controller('ClientController',
function ClientController($scope, Client) {
//Get list of clients
$scope.clients = Client.query(function () {
//preselect first client in array
$scope.selected.client = $scope.clients[0];
});
//necessary for data-binding so that it is accessible in child scopes.
$scope.selected = {};
//Current page
$scope.currentPage = 'start.html';
//For Client nav bar
$scope.clientNavItems = [
{destination: 'features.html', title: 'Features'},
];
//Set current page
$scope.setCurrent = function (title, destination) {
if (destination !== '') {
$scope.currentPage = destination;
}
};
//Return path to current page
$scope.getCurrent = function () {
return 'partials/clients/' + $scope.currentPage;
};
//For nav bar highlighting of active page
$scope.isActive = function (destination) {
return $scope.currentPage === destination ? true : false;
};
//Reset current page on client change
$scope.clientChange = function () {
$scope.currentPage = 'start.html';
};
});
ClientControllerSpec:
'use strict';
var RESPONSE = [
{
"id": 10,
"name": "Client Plus",
"ref": "client-plus"
},
{
"id": 13,
"name": "Client Minus",
"ref": "client-minus"
},
{
"id": 23805,
"name": "Shaun QA",
"ref": "saqa"
}
];
describe('ClientController', function() {
var scope;
beforeEach(inject(function($controller, $httpBackend, $rootScope) {
scope = $rootScope;
$httpBackend.whenGET('http://localhost:3001/clients').respond(RESPONSE);
$controller('ClientController', {$scope: scope});
$httpBackend.flush();
}));
it('should preselect first client in array', function() {
//this fails.
expect(scope.selected.client).toEqual(RESPONSE[0]);
});
it('should set current page to start.html', function() {
expect(scope.currentPage).toEqual('start.html');
});
});
测试失败:
Chrome 25.0 (Mac) ClientController should preselect first client in array FAILED
Expected { id : 10, name : 'Client Plus', ref : 'client-plus' } to equal { id : 10, name : 'Client Plus', ref : 'client-plus' }.
Error: Expected { id : 10, name : 'Client Plus', ref : 'client-plus' } to equal { id : 10, name : 'Client Plus', ref : 'client-plus' }.
at null.<anonymous> (/Users/shaun/sandbox/zong-admin-console-app/test/unit/controllers/ClientControllerSpec.js:43:39)
有没有人对为什么会发生这种情况有任何想法?
另外..因为我刚开始编写AngularJS测试,所以关于我是否设置我的测试错误或是否可以改进的任何评论都将受到欢迎。
更新
包括ClientService:
'use strict';
AdminConsoleApp.services.factory('Client', function ($resource) {
//API is set up such that if clientId is passed in, will retrieve client by clientId, else retrieve all.
return $resource('http://localhost:port/clients/:clientId', {port: ':3001', clientId: '@clientId'}, {
});
});
此外,我通过比较ID来解决问题:
it('should preselect first client in array', function () {
expect(scope.selected.client.id).toEqual(RESPONSE[0].id);
});
答案 0 :(得分:65)
toEqual
进行深度平等比较。这意味着当对象的值的所有属性相等时,对象被认为是相等的。
正如您所说,您正在使用资源,它会为数组中的对象添加一些属性。
因此{id:12}
变为此{id:12, $then: function, $resolved: true}
并不相等。如果您只是测试是否正确设置了值,那么ID检查应该没问题。
答案 1 :(得分:56)
现有答案都建议您对对象进行字符串化,或者创建自定义匹配器/比较函数。但是,有一种更简单的方法:在Jasmine angular.equals()
调用中使用expect
,而不是使用Jasmine的内置toEqual
匹配器。
angular.equals()
会忽略Angular添加到对象中的其他属性,而toEqual
将无法进行比较,例如,$promise
位于其中一个对象上。
我在AngularJS应用程序中遇到了同样的问题。让我们设置场景:
在我的测试中,我创建了一个本地对象和一个本地数组,并期望它们作为对两个GET请求的响应。之后,我将GET的结果与原始对象和数组进行了比较。我使用四种不同的方法测试了这一点,只有一种方法得到了适当的结果。
这是foobar-controller-spec.js的一部分:
var myFooObject = {id: 1, name: "Steve"};
var myBarsArray = [{id: 1, color: "blue"}, {id: 2, color: "green"}, {id: 3, color: "red"}];
...
beforeEach(function () {
httpBackend.expectGET('/foos/1').respond(myFooObject);
httpBackend.expectGET('/bars').respond(myBarsArray);
httpBackend.flush();
});
it('should put foo on the scope', function () {
expect(scope.foo).toEqual(myFooObject);
//Fails with the error: "Expected { id : 1, name : 'Steve', $promise : { then : Function, catch : Function, finally : Function }, $resolved : true } to equal { id : 1, name : 'Steve' }."
//Notice that the first object has extra properties...
expect(scope.foo.toString()).toEqual(myFooObject.toString());
//Passes, but invalid (see below)
expect(JSON.stringify(scope.foo)).toEqual(JSON.stringify(myFooObject));
//Fails with the error: "Expected '{"id":1,"name":"Steve","$promise":{},"$resolved":true}' to equal '{"id":1,"name":"Steve"}'."
expect(angular.equals(scope.foo, myFooObject)).toBe(true);
//Works as expected
});
it('should put bars on the scope', function () {
expect(scope.bars).toEqual(myBarsArray);
//Fails with the error: "Expected [ { id : 1, color : 'blue' }, { id : 2, color : 'green' }, { id : 3, color : 'red' } ] to equal [ { id : 1, color : 'blue' }, { id : 2, color : 'green' }, { id : 3, color : 'red' } ]."
//Notice, however, that both arrays seem identical, which was the OP's problem as well.
expect(scope.bars.toString()).toEqual(myBarsArray.toString());
//Passes, but invalid (see below)
expect(JSON.stringify(scope.bars)).toEqual(JSON.stringify(myBarsArray));
//Works as expected
expect(angular.equals(scope.bars, myBarsArray)).toBe(true);
//Works as expected
});
供参考,以下是console.log
使用JSON.stringify()
和.toString()
的输出:
LOG: '***** myFooObject *****'
LOG: 'Stringified:{"id":1,"name":"Steve"}'
LOG: 'ToStringed:[object Object]'
LOG: '***** scope.foo *****'
LOG: 'Stringified:{"id":1,"name":"Steve","$promise":{},"$resolved":true}'
LOG: 'ToStringed:[object Object]'
LOG: '***** myBarsArray *****'
LOG: 'Stringified:[{"id":1,"color":"blue"},{"id":2,"color":"green"},{"id":3,"color":"red"}]'
LOG: 'ToStringed:[object Object],[object Object],[object Object]'
LOG: '***** scope.bars *****'
LOG: 'Stringified:[{"id":1,"color":"blue"},{"id":2,"color":"green"},{"id":3,"color":"red"}]'
LOG: 'ToStringed:[object Object],[object Object],[object Object]'
注意字符串化对象如何具有额外属性,以及toString
如何产生无效数据,这会产生误报。
expect(scope.foobar).toEqual(foobar)
:这两种方式都失败了。比较对象时,toString显示Angular已添加了额外的属性。比较数组时,内容看起来相同,但这种方法仍然声称它们是不同的。expect(scope.foo.toString()).toEqual(myFooObject.toString())
:这通过了两种方式。但是,这是误报,因为对象没有被完全翻译。这使得唯一的断言是两个参数具有相同数量的对象。expect(JSON.stringify(scope.foo)).toEqual(JSON.stringify(myFooObject))
:此方法在比较数组时给出了正确的响应,但对象比较与原始比较有类似的错误。expect(angular.equals(scope.foo, myFooObject)).toBe(true)
:这是进行断言的正确方法。通过让Angular进行比较,它知道忽略后端添加的任何属性,并给出正确的结果如果对任何人都很重要,我正在使用AngularJS 1.2.14和Karma 0.10.10,并在PhantomJS 1.9.7上进行测试。
答案 2 :(得分:14)
长话短说:添加angular.equals
作为茉莉花匹配器。
beforeEach(function(){
this.addMatchers({
toEqualData: function(expected) {
return angular.equals(this.actual, expected);
}
});
});
那么,你可以按如下方式使用它:
it('should preselect first client in array', function() {
//this passes:
expect(scope.selected.client).toEqualData(RESPONSE[0]);
//this fails:
expect(scope.selected.client).toEqual(RESPONSE[0]);
});
答案 3 :(得分:6)
我遇到了类似的问题,并根据许多方法实现了如下自定义匹配器:
beforeEach(function() {
this.addMatchers({
toBeSimilarTo: function(expected) {
function buildObject(object) {
var built = {};
for (var name in object) {
if (object.hasOwnProperty(name)) {
built[name] = object[name];
}
}
return built;
}
var actualObject = buildObject(this.actual);
var expectedObject = buildObject(expected);
var notText = this.isNot ? " not" : "";
this.message = function () {
return "Expected " + actualObject + notText + " to be similar to " + expectedObject;
}
return jasmine.getEnv().equals_(actualObject, expectedObject);
}
});
});
然后以这种方式使用:
it("gets the right data", function() {
expect(scope.jobs[0]).toBeSimilarTo(myJob);
});
当然,它是一个非常简单的匹配器,并不支持很多情况,但我不需要比这更复杂的东西。您可以将匹配器包装在配置文件中。
检查this answer是否有类似的实现。
答案 4 :(得分:2)
我遇到了同样的问题所以我只是在要比较的对象上调用了JSON.stringify()
。
expect( JSON.stringify( $scope.angularResource ) == JSON.stringify( expectedValue )).toBe( true );
答案 5 :(得分:0)
有点冗长,但在期望失败时会产生有用的信息:
expect(JSON.parse(angular.toJson(resource))).toEqual({ id: 1 });
说明:
angular.toJson
将删除所有角度特定属性的资源,例如$promise
JSON.parse
会将JSON字符串转换回普通的Object(或Array),现在可以将其与另一个Object(或Array)进行比较。