我嘲笑自己的服务在单元测试 [英] Mocking my own service in a unit test

查看:89
本文介绍了我嘲笑自己的服务在单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有需要我的几个其他服务依赖的服务。我怎样才能模拟出来的单元测试?

I have a service that takes several of my other services as a dependency. How can I mock it out for a unit test?

myApp.factory('serviceToTest',
           ['serviceDependency',
    function(serviceDependency) {
        return function(args) {
            return cond(args) ? serviceDependency() : somethingElse();
        };
    }
]);

在上面的例子中,我要模拟出 serviceDependency 这样我就可以验证它被调用。我该怎么做?

In the above example, I want to mock out serviceDependency so I can verify that it was called. How can I do that?

我只是做了测试以下内容:

I could just do the following in the test:

describe("Services", function() {
    describe('serviceToTest', function() {

        myApp.factory('serviceDependency', function() {
            var timesCalled = 0;
            return function() {
                return timesCalled++;
            }
        });

        it('should do foo', inject(function(serviceToTest, serviceDependency) {
            serviceToTest(["foo", "bar", "baz"]);
            expect(serviceDependency()).to.equal(1);
        });
    });
});

这工作正常,需要模拟测试,但它会影响所有后面,这显然是有问题的其他测试的状态。

This works fine for the test that needs the mock, but it then affects the state of all the other tests that follow, which is obviously a problem.

推荐答案

下面是从我的开源项目的例子:<一href=\"https://github.com/lucassus/mongo_browser/blob/f1faf1b89a9fc33ef4bc4eced386c30bda029efa/spec/javascripts/app/services_spec.js.coffee#L25\" rel=\"nofollow\">https://github.com/lucassus/mongo_browser/blob/f1faf1b89a9fc33ef4bc4eced386c30bda029efa/spec/javascripts/app/services_spec.js.coffee#L25 (抱歉的CoffeeScript)。
一般一个规范里面,你必须创建和包括覆盖给予服务一个新的模块。

Here is an example from my open source project: https://github.com/lucassus/mongo_browser/blob/f1faf1b89a9fc33ef4bc4eced386c30bda029efa/spec/javascripts/app/services_spec.js.coffee#L25 (sorry for coffeescript). Generally inside a spec you have to create and include a new module which overrides the given service.

这篇关于我嘲笑自己的服务在单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆