【问题标题】:Service Layer Unit testing with Sinon.js - Error "x" is not a constructor使用 Sinon.js 进行服务层单元测试 - 错误“x”不是构造函数
【发布时间】:2020-09-09 04:43:20
【问题描述】:

我遵循了中型指南: https://medium.com/@tehvicke/integration-and-unit-testing-with-jest-in-nodejs-and-mongoose-bd41c61c9fbc 正在尝试开发测试套件。我的代码和他的完全一样,但我遇到了 TypeError: Tournament is not a constructor

我放了一些代码,所以你可以看到我在做什么。

TournamentService.js

const createTournament = (Tournament) => (tournamentObj) => {
  const {name, creator} = tournamentObj;
  const newTournament = new Tournament({name, creator});
  return newTournament.save();
};

TournamentService.test.js

const TournamentService = require("../TournamentService");
const sinon = require("sinon");

describe("create Tournament test", () => {
  it("creates a tournament", () => {
    const save = sinon.spy();
    console.log("save ", save);
    let name;
    let creator;

    const MockTournamentModel = (tournamentObject) => {
      name = tournamentObject.name;
      creator = tournamentObject.creator;
      return {
        ...tournamentObject,
        save,
      };
    };

    const tournamentService = TournamentService(MockTournamentModel);
    const fintoElemento = {
      name: "Test tournament",
      creator: "jest",
    };

    tournamentService.createTournament(fintoElemento);
    const expected = true;
    const actual = save.calledOnce;

    expect(actual).toEqual(expected);
    expect(name).toEqual("Test tournament");
  });
});

【问题讨论】:

    标签: javascript node.js mongoose jestjs sinon


    【解决方案1】:

    我发现了错误,问题是我试图用箭头函数创建 MockTournamentModel,而不是你应该使用经典函数(或重新编译成经典函数的某些包)

    关键字new做了一些事情:

    • 它创建一个新对象。这个对象的类型就是object。

      - 它设置这个新对象的内部,不可访问,[[prototype]](即 __proto__) 属性作为构造函数的外部、可访问的原型对象(每个函数对象自动具有 原型属性)。

    • 它使 this 变量指向新创建的对象。
    • 它使用新创建的对象执行构造函数 每当提到这一点。
    • 它返回新创建的对象,除非构造函数 返回一个非空对象引用。在这种情况下,该对象 而是返回引用。

    箭头函数根本没有 this、arguments 或其他特殊名称绑定。

    这就是为什么它不能与箭头函数一起使用。希望这能帮助其他人避免我的错误!

    https://zeekat.nl/articles/constructors-considered-mildly-confusing.html

    Arrow Functions and This

    【讨论】:

      猜你喜欢
      • 2021-09-04
      • 2021-12-14
      • 2012-06-28
      • 1970-01-01
      • 2017-11-19
      • 1970-01-01
      • 2015-09-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多