【问题标题】:Node.js unittest Stubbing Own functionNode.js 单元测试 Stubbing 自己的函数
【发布时间】:2025-12-07 17:00:02
【问题描述】:

如果之前有人问过这个问题,我们深表歉意。这是我想在文件getStuff.js 中进行单元测试的模块。我很难存根这里使用的resolveThing 模块。

getStuff.js

const resolveThing = require('./resolveThing.js');

module.exports = async function getStuff(target, stuff) {
  const { element, test, other } = resolveThing(target);

  try {
    return element;
  } catch (error) {
    throw new Error('Did not work.');
  }
};

这是我在单元测试中使用 sinon 进行存根的尝试。但是,当我尝试运行它时,它会出现 TypeError: Cannot stub non-existent own property resolveType 错误。有谁知道我怎样才能让这个测试工作?

const getStuff = require('../com/getStuff');
const resolveThing = require('../com/resolveThing');

const mochaccino = require('mochaccino');

const { expect } = mochaccino;
const sinon = require('sinon');


describe('com.resolveThing', function() {
    beforeEach(function () {
        sinon.stub(resolveThing, 'resolveThing').returns({element:'a',test:'b',other:'c'});
    });

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

    it('Standard message', function() {
        const answer = getAttribute('a','b');
        expect(answer).toEqual('a');
    });
});

【问题讨论】:

    标签: javascript node.js unit-testing tdd sinon


    【解决方案1】:
    sinon.stub(resolveThing, 'resolveThing').returns({element:'a',test:'b',other:'c'});
    

    resolveThing 必须是对象,'resolveThing' 必须是对象中的函数,如果该属性还不是函数,则会引发异常。

    我认为这就是你的情况。

    【讨论】:

    • 是的,我怀疑是这样。你知道我可以如何修改我的测试或函数以使其工作吗?
    • 也许你可以创建一个对象,你可以像这样放置你的函数:const resolveThingObject = {resolveThingFn : resolveThing},然后使用你的新对象:sinon.stub(resolveThingObject,'resolveThingFn').returns ({element:'a',test:'b',other:'c'});