本文介绍了与间谍进行单元测试失败。说间谍从未被称为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我正在测试的代码

eventsApp.factory('userData', ['userResource', function(userResource){
    return{
    getUser: function(userName, callback){
        return userResource.get({userName:userName}, function(user){
        if(callback)
        callback(user);
        });

    };
}]);

这是茉莉花的测试

describe('userData', function(){
    var mockUserResource;

    beforeEach(module('eventsApp'));

    beforeEach(function(){
        mockUserResource = {get: function(){} };

        module(function($provide){
            $provide.value('userResource', mockUserResource);
        });
    });

    it('should make a call to userResource.get with provided userName', inject(function(userData){

        userData.getUser('Bob');
        spyOn(mockUserResource, 'get');
        expect(mockUserResource.get).toHaveBeenCalledWith({userName:'Bob'});
    }));
});

为什么会失败?它说

.toHaveBeenCalled()也失败。

推荐答案

在执行GET请求之前,您不应该设置间谍吗?

Shouldn't you set the spy before doing the GET request?

it('should make a call to userResource.get with provided userName', inject(function(userData){
    //arrange
    spyOn(mockUserResource, 'get');

    //act
    userData.getUser('Bob');

    //assert
    expect(mockUserResource.get).toHaveBeenCalledWith({userName:'Bob'});
}));

编辑: ;)

这篇关于与间谍进行单元测试失败。说间谍从未被称为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 13:29