[英]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.