【问题标题】:How to mock service's response functions in Angular?如何在 Angular 中模拟服务的响应函数?
【发布时间】:2018-01-10 02:48:54
【问题描述】:

所以,在测试中我已经为 AuthService 提供了一个模拟类

    { provide: AuthService, useClass: AuthServiceMock }

这个模拟服务有一个 isAuthorized() 函数,它总是return true

而且,在规范中,看起来像这样

it('init root with LOGIN PAGE if is authenticated, () => {

    expect(comp['rootPage']).toBe(LoginPage); // true!

});

it('init root with WELCOME PAGE if is not authenticated, () => {

    // Here I need to change the result of isAuthorized()
    // so inside the AuthServiceMock returns false
    expect(comp['rootPage']).toBe(WelcomePage); // false :(

});

编辑:添加了描述的完整代码

describe('Component: Root Component', () => {

    beforeEach(async(() => {

        TestBed.configureTestingModule({

            declarations: [MyApp],

            providers: [
              { provide: AuthServiceProvider, useClass: AuthServiceProviderMock },
              ConfigProvider,
              StatusBar,
              SplashScreen
            ],

            imports: [
              IonicModule.forRoot(MyApp)
            ]

        }).compileComponents();

    }));

    beforeEach(() => {

        fixture = TestBed.createComponent(MyApp);
        comp    = fixture.componentInstance;

    });

    it('initialises with a root page of LoginPage if not authorized', () => {

        expect(comp['rootPage']).toBe(LoginPage);

    });

});

【问题讨论】:

    标签: angular unit-testing service mocking


    【解决方案1】:

    您确实在这里遗漏了很多信息,但让我尝试提供帮助。

    希望 AuthServiceMock.isAuthorized 实际上已经是一个 jasmine 间谍。这可以在定义类时完成:

    class AuthServiceMock {
      isAuthorized = jasmine.createSpy('auth.isAuthorized').and.returnValue(true);
    }
    

    如果是这种情况,并且isAuthorized 是间谍,那么您可以在第二次测试中更改间谍的返回值,如下所示:

    it('init root with WELCOME PAGE if is not authenticated',
      inject([AuthService], (mockAuthInstance) => {
        mockAuthInstance.isAuthorized.and.returnValue(false);
        expect(comp.rootPage).toBe(WelcomePage);
      })
    );
    

    在本例中,我们使用了预定义的注入规则,并将模拟服务直接注入到我们的测试中。

    如果isAuthorized还不是间谍,那么你可以在测试中将其设为间谍,如下

    it('init root with WELCOME PAGE if is not authenticated', 
      inject([AuthService], (mockAuthInstance) => {
        spyOn(mockAuthInstance, 'isAuthorized').and.returnValue(false);
        expect(comp.rootPage).toBe(WelcomePage);
      })
    );
    

    【讨论】:

    • 嗨,Jason,问题是我在这个范围内没有 mockAuthInstance。我正在测试 app.component.ts,其中一个在内部注入 AuthService。在这个范围内,我只有 comp 和 fixture 变量。我将编辑主要问题并添加完整的代码示例。谢谢!
    • 这就是inject() 方法的作用。他们会将相同的东西注入您的测试中。在我上面的两个示例中,测试名称后都有inject([AuthService], (mockAuthInstance} => { (it('init root with...')
    猜你喜欢
    • 2020-12-10
    • 2013-01-10
    • 1970-01-01
    • 2017-03-08
    • 1970-01-01
    • 1970-01-01
    • 2013-07-25
    • 1970-01-01
    相关资源
    最近更新 更多