分为两个功能:
public valJson(json, schemaFile: string) {
return new Promise((resolve, reject) => {
this.http.get(schemaFile)
.toPromise()
.then(fileContents => fileContents.json())
.then((schema) => {
let ajv = new Ajv({allErrors: true});
ajv.validate(schema, json) ?
resolve() :
reject(new Error("JSON does not conform to schema: " + ajv.errorsText()));
}, err => reject(
new Error("Unable to get schema file contents:" + err))
);
});
};
这个功能确实有3件事情,所以单元测试并不是很好。
如何解决这些问题以使每个任务都可以测试?
尝试打破实际的验证部分并不顺利:
public valJson(json, schemaFile: string) {
return new Promise((resolve, reject) => {
this.http.get(schemaFile)
.toPromise()
.then(fileContents => fileContents.json())
.then((schema) => {
this.valJ(schema)
}, err => reject(
new Error("Unable to get schema file contents:" + err))
);
});
};
valJ(schema, json) {
let ajv = new Ajv({ allErrors: true });
if ajv.validate(schema, json)
return resolve()
reject(new Error("JSON does not conform to schema: " + ajv.errorsText()));
}
}
更新 - 根据反馈,我试图停止使用匿名函数,然后我将尝试不创建新的承诺。我在这里:
public valJson(json, schemaFile: string) {
return new Promise((resolve, reject) => {
var getFilePromise = this.http.get(schemaFile)
.toPromise();
var parseToJsonPromise = getFilePromise
.then(contents => this.toJson(contents));
var validateJsonPromise = parseToJsonPromise.then(schema => this.valJ(schema, json, resolve, reject),
err => reject(
new Error("Unable to get schema file contents:" + err))
);
});
};
toJson(fileContents): any {
return fileContents.json()
}
valJ(schema, json, resolve, reject): any {
let ajv = new Ajv({ allErrors: true });
ajv.validate(schema, json) ?
resolve() :
reject(new Error("JSON does not conform to schema: " + ajv.errorsText())
);
}
答案 0 :(得分:1)
一种可能的方法:
public valJson(json, schemaFile: string) {
return this.fetchSchema(schemaFile)
.then(res => this.parseSchema(res))
.then(schema => this.validateWithSchema(json, schema));
}
fetchSchema(url) {
return this.http.get(url).toPromise();
}
parseSchema(response) {
return response.json();
}
validateWithSchema(json, schema) {
let ajv = new Ajv({allErrors: true});
if (!ajv.validate(schema, json)) {
throw new Error("JSON does not conform to schema: " + ajv.errorsText())
}
}