在单元测试中,我必须创建具有大量属性的存根。
所以我会有这样的界面:
interface Person {
id: string;
name: string;
age: number
...
}
然后,我将必须创建一个实现此接口的对象,并将一些值传递给每个属性。 茉莉花不具有接收接口并返回具有默认值的对象的功能吗?
在上面的示例中,我将得到:
const stub: Person = createStubObj<Person>();
stub.id // ""
stub.name // ""
stub.getAge // 0
我做了一些研究,但没有发现任何有用的东西。
createSpyObj 似乎对我没有帮助,因为我没有想要监视的任何功能。该对象仅具有属性。
当HTTP请求返回复杂对象(许多属性,嵌套属性)时,可能会发生这种情况。我想知道在那种情况下如何模拟该对象,而无需为每个属性指定值。
类似于该库的操作:https://www.npmjs.com/package/ts-auto-mock#usage
我想知道这是否也可以在茉莉花中实现,或者是否有更好的方法
答案 0 :(得分:1)
我倾向于创建特定的模拟对象,可以使用TestBed提供程序注册将其注入到被测组件中:
TestBed.configureTestingModule({
providers: [
TestComponent,
{ provide: RealInterfaceType, useValue: new MockObjectType() }
]
});
然后可以在模拟对象中定义适当的属性值。同样,您可以通过设置间谍将模拟对象用作从属服务的响应:
serviceSpy = jasmine.createSpyObj('SomeService', ['someFunction']);
serviceSpy.someFunction.and.returnValue(new MockObjectType());
对于http调用,我通常如下进行测试...
let injector: TestBed;
let service: TestService;
let httpMock: HttpTestingController;
const expectedResponse: TestObject = new TestObject();
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [
TestService
});
injector = getTestBed();
service = injector.get(TestService);
httpMock = injector.get(HttpTestingController);
});
afterEach(() => {
httpMock.verify();
});
describe('someFunction', () => {
it('should return an Observable<UserAuthResponse>', () => {
service.someFunction().subscribe(response => {
expect(response).toBe(expectedResponse);
});
const req = httpMock.expectOne('http://the-expected-url');
expect(req.request.method).toBe('GET');
// return the static expected value
req.flush(expectedResponse);
});
});
这只是测试预期的http方法和URL。