使用Mongoose进行异步玩笑测试

时间:2017-08-07 10:53:41

标签: node.js mongodb mongoose jestjs

所以我的mongoose模型周围有一个包装器,看起来像这样

export default class UserModel extends BaseModel {
  constructor(url) {
    super(url, "User");
    this.schema = new mongoose.Schema(userSchemaParams);
    this.name = "User";
  }

  async insert(data) {
    if (!this.connection) {
      throw new Error("No connection, please connect before using UserModel");
    }
    if (!this.model) {
      this.model = this.connection.model(this.name, this.schema);
    }
    return await this.model.create(data);
  }
}

使用此代码时,我这样做 -

try {
      const userModel = new UserModel("mongodb://localhost:27017/doc_snaphunt");
      await userModel.connect();
      return await userModel.insert(dbUserData);
    } catch (error) {
      throw error;
    }

在我的开玩笑代码中,我有这个 -

  UserModel.prototype.insert = jest.fn();
  UserModel.prototype.connect = jest.fn();
createUser(JSON.stringify(userData));
  expect(UserModel.prototype.connect).toHaveBeenCalled();
  // TODO fix this
  expect(UserModel.prototype.insert).toHaveBeenCalled();

最后一个断言失败了。

我已经证明插入实际上是被调用的 - 它失败了,因为断言在调用insert函数调用之前运行。

如何使这项工作?我想添加一个await会解决这个问题吗?

0 个答案:

没有答案
相关问题