Jest.js 如何模拟由构造函数调用的JavaScript示例方法

yquaqz18  于 5个月前  发布在  Jest
关注(0)|答案(1)|浏览(110)

是否可以模拟由构造函数调用的JavaScript示例方法?
例如,给予这种设计

class Example {
   constructor() {
      // other stuff
      helper();
      // other stuff
   }

   helper() {
      // ....
   }
}

字符串
有没有一种方法可以在Jest中编写一个单元测试来验证构造函数是否调用了helper(而不是验证helper中的某个特定行是否运行)?
通常,如果我想模拟一个示例方法,我会这样做:

e = new Example()
   e.helper = jest.fn()


但是,在本例中,helper将在我设置mock之前被调用。
我知道我可以通过调用构造函数来测试helper,但是
1.分别测试它们将帮助我更好地组织测试代码,
1.在一种情况下,helper调用了我不想进行单元测试的代码--我不想尝试模拟helper中的所有内容,我只想验证是否调用了帮助程序。

3zwtqj6y

3zwtqj6y1#

你可以这样做:
Example.js:

class Example{
  constructor() {
    this.someValue = this.helperFunction();
  }

  helperFunction() {
    // Some implementation details
    return 'Hello, World!';
  }
}

module.exports = Example;

字符串
Example.test.js:

const Example = require('./Example');

// Mock the helper function
jest.mock('./Example', () => {
  return {
    ...jest.requireActual('./Example'),
    helperFunction: jest.fn(),
  };
});

describe('Example', () => {
  it('should call helperFunction during construction', () => {
    // Arrange
    const myClassInstance = new Example();

    // Assert
    expect(Example.prototype.helperFunction).toHaveBeenCalled();
    // You can also check other expectations based on the specific behavior of your code
  });
});

相关问题