我正在测试我在网上找到的外部凉亭组件。它在我的代码上按预期工作,但我无法对其进行单元测试。
我的代码:
控制器:
function testCtrl(externalComponent) {
//other codes
externalComponent.loadFile('test.txt').then(function(res) {
console.log(res)
})
单元测试
describe..
beforeEach(module('testApp'));
beforeEach(inject(function($injector) {
externalComponent = $injector.get('externalComponent');
$rootScope = $injector.get('$rootScope');
$httpBackend = $injector.get('$httpBackend');
});
describe('my test', function () {
beforeEach(function () {
});
it('should test external component', function () {
//not sure how to test external component.
$httpBackend.flush()
});
})
}
答案 0 :(得分:1)
下面的代码是根据代码测试单元测试的一般方法
控制器代码:
function testCtrl(externalComponent,$scope) {
//other codes
externalComponent.loadFile('test.txt').then(function(res) {
$scope.data = res;
})
}
测试代码:
beforeEach(module('testApp'));
beforeEach(inject(function($injector) {
$controller = $injector.get('$controller')
externalComponent = $injector.get('externalComponent');
$rootScope = $injector.get('$rootScope');
$httpBackend = $injector.get('$httpBackend');
});
describe('my test', function () {
var testCtrl, data = {a:1}, $scope = {};
beforeEach(function () {
$httpBackend.when('GET', '/test.txt')
.respond(data)
testCtrl = $controller('testCtrl', { $scope: $scope });
});
it('should test external component', function () {
//not sure how to test external component.
$httpBackend.flush()
expect($scope.data).toEqual(data);
});
})
}
解释: