【问题标题】:Async Function stubbing in sinon invokes actual function callsinon 中的异步函数存根调用实际的函数调用
【发布时间】:2019-07-17 01:04:18
【问题描述】:

当我使用 mocha 运行单元测试时,我有一个异步函数,我看到它没有存根。我没有看到 console.log 正在打印登录函数,看起来实际的 getUser() 函数被调用.

// User.js

class User {
  async _getUser(client, email) {
    let result = await new userApi().getUser(new UserInfo(email, email));
    console.log("Get result " + JSON.stringify(result));
    let user = result.users[0];

    console.log("Get User " + JSON.stringify(user));
    return user;
  }
}
module.exports = User;


// Usertest.js

const chai = require("chai");
const sinon = require("sinon");
var chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised).should();
const expect = chai.expect;
const UserInfo = require("../src/model/userInfo");
const User = require("../src/model/user");

describe("Test LogInCommand", function() {
  let user, sandbox;

  beforeEach(() => {
    sandbox = sinon.sandbox.create();
    user = new user();
  });

  afterEach(function afterEach() {
    sandbox.restore();
  });

  it("getUser function", function(done) {
    let User = new UserInfo("email", "email", "station");
    sandbox
      .stub(userApi, "getUser")
      .withArgs(User)
      .returns(
        Promise.resolve({
          users: [
            {
              id: 1
            }
          ]
        })
      );
    sandbox.stub(logger, "info");
    let result = logInCommand._getUser(client, "email", "stationid");
    done();
  });
});

【问题讨论】:

  • 能发一下userApi代码吗?
  • 什么是userApi?在User.js中是如何导入的,在Usertest.js中是如何导入的?

标签: javascript unit-testing mocha.js es6-promise sinon-chai


【解决方案1】:

我假设userApi 是一个类,所以为了存根它,我们必须像下面这样:

sandbox.stub(userApi.prototype, "getUser").withArgs(User)...

我们必须添加prototype 来存根类的方法。

我还在您的测试中找到了一些要修复的问题,这是因为您没有将 logInCommand._getUser 视为异步调用。所以,这里是更新后的代码。

it("getUser function", async function() { // remove `done` and let's use async/await here
  let User = new UserInfo("email", "email", "station");
  sandbox
    .stub(userApi.prototype, "getUser") // add prototype
    .withArgs(User)
    .resolves({ // in new sinon, they have `resolves` method
        users: [
          {
            id: 1
          }
        ]
      });    
  sandbox.stub(logger, "info");
  let result = await logInCommand._getUser(client, "email", "stationid"); // add await because this method is async
  // remove done()
});

希望对你有帮助

【讨论】:

    猜你喜欢
    • 2021-09-04
    • 2018-02-23
    • 2016-01-02
    • 2016-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-25
    相关资源
    最近更新 更多