繁体   English   中英

Angular 5依赖项注入(服务到测试文件)

[英]Angular 5 dependency injection (service to test file)

我正在学习大理石测试,并且在学习本教程时达到了简单测试如下所示的程度:

user-effects.service.spec.ts

imports ...
describe('User Effects', () => {
    it('basic test', () => {
        const source = cold('--a', { a: { type: LOGIN } });
        const effects = new UserEffectsService(new Actions(source), ?? );

        const expected = cold('--b', { b: { type: LOGIN_SUCCESS } });
        expect(effects.login$).toBeObservable(expected);
    });
});

但是我的UserEffectsService需要2个参数

user-effects.service.ts

@Injectable()
export class UserEffectsService {
    constructor(private actions$: Actions, private userService: UserDataService) {
    }
    ...

也许我可以在那里传递一个新的UserDataService实例,但是UserDataService需要另外2个参数,等等,并且会很长。 如果没有构造函数,我找不到注入依赖项的任何解决方案。 感谢您如何处理此案的任何提示。

@编辑任何人? :D

有一种方法可以做到这一点。

在您的beforeEach您可以注入以下服务:

let service = TestBed.get(UserDataService)

那么当您创建新的效果实例时,您只需传递服务实例即可。

const effectService = new UserEfectsService(action,service); 

如果您有多种服务,则可以执行以下操作:

let [service1, service2, serviceN] = [Service1, Service2, ServiceN].map(TestBed.get);

模拟注射到您的服务中。

const actionsMock = {};
const userServiceMock = {};

然后,将当前服务中使用的所有变量和函数放入模拟中。

例如,假设您使用用户服务中的getAllUsers函数:然后将其添加到模拟中:

const userServiceMock = {
  getAllUsers: () => Observable.of([/* array of users */])
};

现在,您可以创建任意数量的对象:

const instance = new UserEffectsService(actionsMock, userServiceMock);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM