Split into two separate functions:
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))
);
});
};
This function actually performs 3 distinct tasks which makes it difficult to unit test.
- Retrieve file contents
- Parse the contents to JSON
- Validate the JSON data
How could we break down this function to enable unit testing for each task?
An initial attempt at separating the validation part is not progressing as intended:
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()));
}
Update - Based on feedback, making an effort to avoid using anonymous functions and then attempting to eliminate creating a new promise. Progress so far:
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());
);
}