我有这样的功能
$scope.openMail=function(mail){
DocumentTypes.getDocument(function(response){
$scope.documentTypes=response.result;
$log.log("documentTypes",$scope.documentTypes);
})
}
以上乐趣的规格是
it("should test open mail", function(){
scope.documentTypes=[{"type":"pdf"},{"type":"xml"}];
spyOn(documentTypes,"getDocument").and.callFake(function(){
return scope.documentTypes;
});
var mail='back';
scope.openMail(mail);
expect(scope.documentTypes).toEqual({"type":"pdf"},{"type":"xml"});
})
所以代码没有覆盖function(response){}
答案 0 :(得分:2)
您的测试有几个问题:
spyOn(documentTypes,"getDocument")
而不是spyOn(DocumentTypes,"getDocument")
scope.documentTypes
初始化为测试的预期结果,即无论代码做什么,测试都会通过(除非你得到例外)mail
参数以下是我将如何测试它:
describe('$scope.openMail', function() {
beforeEach(function() {
spyOn(DocumentTypes, 'getDocument');
});
it('uses DocumentTypes.getDocument service to get the document types', function() {
$scope.openMail('test_mail');
expect(DocumentTypes.getDocument).toHaveBeenCalledWith(jasmine.any(Function));
});
describe('provides a callback function that', function() {
beforeEach(function() {
DocumentTypes.getDocument.and.callFake(function (callback) {
callback('test_document_types');
});
});
it('stores the document types on the scope', function() {
$scope.openMail('test_mail');
expect($scope.documentTypes).toEqual('test_document_types');
});
// Note: This is optional, depending on whether you test logging or not
it('logs the document types', function() {
spyOn($log, 'log');
$scope.openMail('test_mail');
expect($log.log).toHaveBeenCalledWith('documentTypes', 'test_document_types');
});
});
});
答案 1 :(得分:0)
我在这里完全错了,但如果对DocumentTypes.getDocument(...)的调用是异步调用,则可能需要在调用{{1}后调用scope.apply()
来触发摘要周期}
答案 2 :(得分:0)
假设您正在将DocumentTypes注入您的控制器或您拥有该openMail函数的任何内容,您可以在执行测试时模拟它。一种方法是使用$ provide服务。
如果使用karma-chai-spies,这个模拟看起来像这样:
stubs = {
DocumentTypes: {
getDocument: chai.spy(function(callback)
{
callback({
result: [
"type"
]
});
})
}
};
然后在单元测试中使用$ provide提供它:
beforeEach(function()
{
module(function($provide)
{
$provide.value("DocumentTypes", stubs.DocumentTypes);
});
});
使用karma-mocha和karma-chai,测试本身可能看起来像这样:
it("should test open mail", function()
{
var controller = $controller('myController', {
$scope: stubs.$scope
});
stubs.$scope.openMail("mail");
expect(stubs.$scope.documentTypes).to.deep.equal([
"type"
]);
expect(stubs.DocumentTypes.getDocument).to.have.been.called.once();
});