sinon中的异步函数存根调用实际的函数调用

问题描述 投票:0回答:1

当我使用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();
  });
});
javascript unit-testing mocha es6-promise sinon-chai
1个回答
0
投票

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

希望能帮助到你

© www.soinside.com 2019 - 2024. All rights reserved.