[英]Unit Testing Model Binding in Angular 5 with Jasmine
我正在尝试编写一个单元测试,以测试从components方法调用返回的JSON数据是否成功绑定到打字稿模型。
我的模型如下所示:
export interface IPlayerAccount {
playerId: number;
name: string;
phone: number;
street: string;
postcode: string;
state: string;
country: string;
}
此IPlayerAccount数组使用方法定义填充在ngOnInit上:
getPlayerAccounts(playerId: number)
这是我的Jasmine单元测试,用于测试json数据是否成功找到到打字稿IPlayerAccount模型。
it('check that array of players successfully bind to component accounts players array', async () => {
fixture.detectChanges();
IPlayerAccount accounts = new IPlayerAccount();
var account1 = new IPlayerAccount();
account1.playerId = 1;
account1.name = 'Ben';
account1.phone = 12345;
account1.street = 'Cloud Street';
account1.postcode = 111;
account1.state = 'VIC'
account1.country = 'AU';
var account2 = new IPlayerAccount();
account2.playerId = 2;
account2.name = 'James';
account2.phone = 6789;
account2.street = 'Jamming Street';
account2.postcode = 2323;
account2.state = 'VIC'
account2.country = 'AU';
component.accounts.push(account1);
component.accounts.push(account2);
IPlayerAccount[] returnedAccounts = component.getPlayerAccounts(1);
// Need test methods here, such as expect. Not really sure how to simulate the method being called in Angular front-end testing
// Is the above a good way to asynchronously test the getPlayerAccounts method of the component
});
请注意,我还有以下用于组件的Mock。
public GetPlayerAccounts(successCallback: (data) => void, errorCallback: (data) => void, playerId: number): void {
let data = [{ "playerId": 1, "name": "Ben", "phone":"12345" "street": "Cloud Street", "postcode": "111", "state": "VIC", "country": "AU" },{ "playerId": 2, "name": "James", "phone":"6789" "street": "Jamming Street", "postcode": "2323", "state": "VIC", "country": "AU" }];
successCallback(data);
}
如何将模拟数据与json数据再与IPlayerAccount进行匹配? 到目前为止,我的方法好吗? 解决这个单元测试还有更好的选择吗?
任何帮助将是巨大的!
首先模拟你的玩家
const fakePlayers = [ {
playerId: 1,
name: 'Mark'
...
},
{...}
]
这是测试,可以说getPlayerAccounts设置了一个属性名称loadedPlayer及其结果
beforeEach(async(() => {
...
fixture = TestBed.createComponent(PlayerComponent);
component = fixture.componentInstance;
...
}));
it('should get players', async(() => {
fixture.detectChanges();
component.players = fakePlayers;
component.playerId = 1;
component.ngOnInit();
fixture.whenStable().then(() => {
fixture.detectChanges();
expect(component.loadedPlayer).toEqual(fakePlayers[1]);
});
}));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.