【问题标题】:How to mock a method in the very same service如何在同一服务中模拟方法
【发布时间】:2016-01-19 04:55:30
【问题描述】:

我有这样的服务:

var myApp = angular.module('myApp', []);

myApp.factory('myService', function() {

    var a = function() {
        return b();
    }

    function b() {
        return 'foo';
    }

    return {
        a: a
    };
});

现在,我想通过模拟 b(); 来测试 a();,例如通过使其返回 bar。我的测试是这样的:

it('should call a() and return string bar', function() {
    // mock function b() here
    expect(myService.a()).toBe('bar');
});

在这种情况下,我如何模拟 b();?我正在考虑使用$provide,但它似乎只适用于$inject

【问题讨论】:

    标签: javascript angularjs unit-testing angularjs-service karma-jasmine


    【解决方案1】:

    您可以使用 spyOn。这是一个例子:

    beforeEach(function(){
        spyOn(myService, 'b').and.returnValue('bar');
    });
    
    it('should call a() and return string bar', function() {
        expect(myService.a()).toBe('bar');
    });
    

    在此处阅读有关间谍活动的更多信息http://jasmine.github.io/2.0/introduction.html#section-Spies

    【讨论】:

    • 感谢您的回答,我忘了提及 服务 没有返回b();。这仍然可以通过使用 sies 实现吗?我已经更新了我的问题。
    • 你可以使用spyOn(myService, 'b').and.returnValue('bar');而不在describe()块和myService = {b: function(value) {}};中启动myService吗?因为它会模拟整个服务,包括a();
    • 不,你不能我假设你已经初始化了它。关于你之前的问题,很遗憾我不知道。
    猜你喜欢
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    • 2013-09-12
    相关资源
    最近更新 更多