这个示例应用程序具有 level db Node JS 库,但我的服务器当前没有安装 level db,我不需要它。
如何编写一个简单的类来模拟 API 调用。
store 变量是我想要模拟的库,它有 2 个 API 调用:
store.put
store.get
它有 2 个 API 调用:
const store = level('./data/dbname123', { valueEncoding: 'json' });
save() {
debug(`saving id: ${this.id}`);
const properties = attributes.reduce((props, attr) => {
props[attr] = this[attr];
return props;
}, { fields: this.fields });
return new Promise((resolve, reject) => {
store.put(this.id, properties, (error) => {
if (error) { return reject(error); }
resolve(this);
});
});
}
static find(id) {
debug(`fetching id: ${id}`)
return new Promise((resolve, reject) => {
store.get(id, (error, properties) => {
if (error) { return reject(error); }
resolve(new Ticket(properties));
});
});
}
我怎样才能快速 mock 那些?我不太熟悉这种 JavaScript 风格,但由于 Promise 包装器,我不确定这是否是异步调用?
最佳答案
您可以创建一个带有 put
和 get
方法的对象来模拟这些方法的功能。只需确保您的函数遵循预期的约定 - 例如,如果出现问题,则调用回调并将错误作为第一个参数。
显然这可能会涉及更多,并且有像Sinon这样的工具如果您必须模拟现有函数,这会有所帮助。
例如:
// simple mocks for store.get and store.put
let store = {
put(id, properties, fn){
// add whatever behavior you need and call callback fn
fn(null) // calling with null indicates no error.
},
get(id, fn){
// make some properties
let props = {
someProperties: "Hello",
id: id
}
// call callback
fn(null, props)
}
}
function save() {
return new Promise((resolve, reject) => {
store.put('id', 'properties', (error) => {
if (error) { return reject(error); }
resolve();
});
});
}
function find(id) {
return new Promise((resolve, reject) => {
store.get(id, (error, properties) => {
if (error) { return reject(error); }
resolve(properties);
});
});
}
// try them out
find("21")
.then(console.log)
save()
.then(() => console.log("done"))
关于javascript - 如何编写返回异步的 API 调用的简单模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51901937/