打破承诺链成单独的功能

时间:2017-01-24 22:14:12

标签: javascript typescript promise

分为两个功能:

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件事情,所以单元测试并不是很好。

  1. 获取文件内容
  2. 将它们解析为json
  3. 验证json
  4. 如何解决这些问题以使每个任务都可以测试?

    尝试打破实际的验证部分并不顺利:

    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())
        );
    }
    

1 个答案:

答案 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())
  }
}