【发布时间】:2018-05-11 15:03:00
【问题描述】:
我正在尝试编写一个单元测试来测试从组件方法调用返回的 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 数据是否成功找到 typescript 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);
}
如何将 mock 中的数据与 json 数据匹配到 IPlayerAccount?到目前为止我的方法好吗?解决这个单元测试有什么更好的选择吗?
任何帮助都会很棒!
【问题讨论】:
-
此代码不是有效的 JavaScript 或 TypeScript。因此,我不确定您要做什么。你不能实例化 TypeScript 接口。
-
另外,我真的不明白你在做什么。这个测试没有任何异步。您可以随时开始调用茉莉花的期望。
标签: angular unit-testing model jasmine