gpt4 book ai didi

angularjs - 如何在另一个服务中从外部文件注入(inject)服务的模拟

转载 作者:行者123 更新时间:2023-12-04 20:39:38 25 4
gpt4 key购买 nike

我正在测试一个依赖于另一个服务 B 的服务 1。通常这样做的正确方法是使用 $provide注入(inject)A之前的对象。但是,我有两个约束:

  • 服务 B 的 mock 存储在另一个文件中,因为我在多个测试中重复使用它(如下所示,我只是注册了一个新的 Angular 服务)
  • 我需要在测试中的某些时候初始化此服务 B(设置 promise )

  • 问题是,到目前为止(我正在测试 Controller ),为了能够从我的测试中访问服务 B,我需要注入(inject)它。但是要在 $provide 中模拟它我需要在我的测试中已经可以访问它,这会带来问题,因为 $provide需要在任何 inject() 之前使用.这是我的测试:
    describe('viewsListService', function() {
    var viewList,
    queryDeferred,
    mockViews,
    $scope;

    beforeEach(module('BoardMocks'));
    beforeEach(module('Board'));

    beforeEach(inject(function(mockViewsService) {
    var query = {};
    mockViewsService.init({}, query);
    queryDeferred = query.deferred;

    mockViews = mockViewsService.mock;
    }));

    beforeEach(function() {
    angular.mock.module('Board', function ($provide) {
    $provide.value('Views', mockViews);
    });
    });

    beforeEach(inject(function(viewsListService, $rootScope) {
    $scope = $rootScope.$new();
    viewList = viewsListService;

    // Initialisation of the viewsListService
    viewList.init();
    queryDeferred.resolve([1]);
    $scope.$digest();
    }));

    describe('getAllViews', function() {
    var allViews;

    beforeEach(function() {
    allViews = viewList.getAllViews();
    });

    it('should return all the views', function() {
    expect(allViews.length).toBe(1);
    });
    });
    });

    这给了我一个 Error: Injector already created, can not register a module! ,指向 angular.mock.module 调用。

    我将我的模拟服务移动到另一个模块,想也许它会解决问题,想知道注入(inject)器是否特定于一个模块,但它似乎不是(在第一个 beforeEach(module('Board')); 之后移动 inject() 不' t 解决问题。

    您是否有任何想法让它工作,同时将模拟保留在外部文件中(我可以不将其注册为 Angular 服务,而只是将其注册为普通对象,如果它可以解决这个问题)。

    最佳答案

    经过大量环顾后,我找到了 Valentyn Shybanov 的答案,解释了如何做到这一点。其实很简单。我会把它留在这里给其他迷失的灵魂。

    Actually in AngularJS Dependency Injection uses the 'last wins' rule. So you can define your service in your test just after including your module and dependencies, and then when service A that you're testing will request service B using DI, AngularJS will give mocked version of service B.



    因此,如果您想模拟“ View ”服务。您创建一个包含“ View ”服务的“BoardMocks”模块。如果在“Board”之后包含“BoardMocks”,则在测试期间将使用模拟的“Views”服务。

    在此处查看原始答案:
    Injecting dependent services when unit testing AngularJS services

    关于angularjs - 如何在另一个服务中从外部文件注入(inject)服务的模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28763519/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com