Angular 2单元测试:注入Typemoq对象 [英] Angular 2 Unit Testing: Injecting Typemoq objects

查看:212
本文介绍了Angular 2单元测试:注入Typemoq对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Typescript中的Angular 2(RC4)服务实现单元测试。要测试的服务(计算)使用许多其他组件(Bausparen),它们使用组件(BausparenInput)。所有组件都声明为@Injectable()。

I'm implementing a unit test for a Service in Angular 2 (RC4) in Typescript. The service to test ("Calculation") uses a lot of other components ("Bausparen"), which on their part use components ("BausparenInput"). All components are declared @Injectable().

我试图使用 Typemoq 并在运行测试之前注入它们。无论如何,它不起作用:

I tried to mock the depending components like Bausparen using Typemoq and injecting them before running the tests. Anyway, it doesn't work:

FAILED TESTS:
Calculation Service
× should return empty array when fromYear > toYear
  PhantomJS 2.1.1 (Windows 7 0.0.0)
factory
factory
resolveReflectiveFactory
resolveReflectiveProvider
map@[native code]
apply@[native code]
call@[native code]
call@[native code]
Call
map
resolveReflectiveProviders
resolve
resolveAndCreateChild
createInjector
execute

内部 Jasmines 描述函数,代码如下:

Inside Jasmines describe function, the code looks like this:

let calcInput = x => x.calc(TypeMoq.It.isAnyNumber(), TypeMoq.It.isAnyNumber());
let calcInputFormer = x => x.calc(TypeMoq.It.isAnyNumber(), TypeMoq.It.isAnyNumber(), TypeMoq.It.isAnyNumber());
let calcOutput = (y, m) => new CalcOutput();
let calcOutputFormer = (y, m, f) => new CalcOutput();
let bausparenMock = TypeMoq.Mock.ofType(Bausparen);
bausparenMock.setup(calcInput).returns(calcOutput);
bausparenMock.setup(calcInputFormer).returns(calcOutputFormer);

beforeEach(() => {
  addProviders([CalculationService,
    { provide: Bausparen, useClass: bausparenMock }]);
});

it('should return empty array when fromYear > toYear',
  inject([CalculationService], (calculation: CalculationService) => {
    let result = calculation.getValues(6, 2017, 6, 2016);
    expect(result.length).toBe(0);
}));

和类的签名是这样的:

class Bausparen implements Calculation {
  calc(year: number, month: number, formerAmount?: number): CalcOutput {...}
}

错误消息并没有真正告诉我任何事情。如果在我的模拟设置或注入中它是一个问题,我甚至不会得到它。有没有人之前有类似的错误?

The error message doesn't really tell me anything. I don't even get if it's a problem in the setup of my mock or in injecting it. Has anybody had a similar error before?

推荐答案

你应该替换:

{ provide: Bausparen, useClass: bausparenMock }

with :

{ provide: Bausparen, useValue: bausparenMock }

因为mock是值不是类

Because mock is value not a class

还要看 ts-mockito

这篇关于Angular 2单元测试:注入Typemoq对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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