几周前我开始使用 ng-mocks,因为我认为它是为这种情况而设计的,但对于我的生活,我无法弄清楚如何实现它。
简而言之,在定义 MockBuilder/MockRender 之后,可以在嵌套的描述/测试中更改模拟提供者的值吗?
在我的应用程序中,我经常有依赖于根据上下文提供不同数据的服务的组件。在这是静态的情况下,这很容易测试。我将在这里使用 ActivatedRoute 作为示例,因为它让我感到悲伤:
const mockActivatedRoute = { snapshot: { params: { id: 1 } };
describe('MyComponent', () => {
MockInstance.scope('all');
beforeEach(() => {
return MockBuilder(MyComponent, MyModule)
.provide({ provide: ActivatedRoute, useValue: mockActivatedRoute })
});
beforeEach(() => {
fixture = MockRender(MyComponent);
component = fixture.point.componentInstance;
});
// Imagine the component has a routeId provided by the ActivatedRoute
it('should have an id of 1', () => { expect(component.routeId).toEqual(1); });
});
到目前为止,一切都很好。
但在那次测试之后,我想运行另一个修改服务的套件;说id
现在将是2。我认为这是角色MockInstance
:能够为给定的测试动态更改提供的服务等。
因此,为了继续我的示例,现在我将describe
在第一次测试之后在第一个中添加一个嵌套:
describe('MyComponent', () => {
...
describe('when it inits with a different id', () => {
MockInstance.scope();
beforeEach(MockInstance(mockActivatedRoute, () => {
snapshot: { params: { id: 2 } }
}));
it('should have an id of 2', () => { expect(component.routeId).toEqual(2); });
});
});
该测试将失败,因为新的模拟值从未实现并且routeId
保持不变。
我意识到这是一个糟糕的例子。我已经用很多不同的方式重写了这些测试,使用MockInstance.remember
或尝试初始化服务实例本身,但没有任何成功。据我所知,MockBuilder 和 MockInstance 似乎并不是要一起使用的,而且在 ng-mocks 网站上也没有这样的例子。似乎为这种情况构建测试的唯一方法是describes
使用自己的 MockBuilder 和 MockRender 单独构建每个测试。
还是我最好的选择只是routeId
公开并直接操纵它?