我正在Typescript中为Angular 2(RC4)中的服务实现一个单元测试。要测试的服务(“计算”)使用了许多其他组件(“Bauspren”),这些组件本身使用组件(“BausfeInput”)。所有组件都声明为@Inject table()。
我试图使用Typemoq模拟依赖组件,例如Bauspren并在运行测试之前注入它们。无论如何,它不起作用:
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
茉莉描述函数内部,代码如下:
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 {...}
}
错误信息并没有真正告诉我任何事情。我甚至不知道这是不是我的模拟设置或注入中的问题。以前有人遇到过类似的错误吗?
{ provide: Bausparen, useClass: bausparenMock }
{ provide: Bausparen, useValue: bausparenMock }
因为模拟是价值而不是阶级
也看看ts-mockito