jestjs - Mock.mockImplementation() 不工作

标签 jestjs

我有一个服务类

服务.js

class Service {
}
export default new Service();

我正在尝试为此提供一个模拟实现。如果我使用这样的东西:
jest.mock('./Service', () => { ... my mock stuff });

它工作正常,但是我无法访问在模拟之外声明的任何变量,这有点限制,因为我想重新配置模拟返回的内容等。

我试过这个(灵感来自另一篇 StackOverflow 文章:Service mocked with Jest causes "The module factory of jest.mock() is not allowed to reference any out-of-scope variables" error)
import service from './Service';

jest.mock('./Service', () => jest.fn);

service.mockImplementation(() => {
    return { ... mock stuff }
);

不幸的是,当我尝试运行它时,出现以下错误:
TypeError: _Service2.default.mockImplementation is not a function

最佳答案

我和@Janos 有同样的问题,其他答案也没有帮助。你可以做两件事:

  • 如果您只需要模拟服务中的一个函数,请在您的测试文件中:
    import service from './Service';
    
    jest.mock('./Service', () => jest.fn());
    
    service.yourFunction = jest.fn(() => { /*your mock*/ })
    

  • 如果您需要模拟整个模块:
    假设你的 service.js 在 javascript/utils 中,创建一个 javascript/utils/_mocks_ 并在其中创建一个 service.js 文件,然后你可以在这个文件中模拟整个类,例如:
    const myObj = {foo: "bar"}
    
    const myFunction1 = jest.fn(() => { return Promise.resolve(myObj) })
    
    const  myFunction2 = ...
    
    module.exports = {
      myFunction1,
      myFunction2
    }
    
    然后在您的测试文件中添加:
    jest.mock('./javascript/utils/service')
    
    ...从模拟文件导出的函数将通过您的测试文件执行来命中。
  • 关于jestjs - Mock.mockImplementation() 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45771844/

    相关文章:

    javascript - 如何使用 enzyme 作为实例()测试功能组件内部的方法,为浅包装器返回 null?

    javascript - 如何使用 Jest 测试 img.onload?

    node.js - Jest 模拟 Stripe

    unit-testing - Jest 进行 React 快照测试 - 失败的 Prop 类型 : Invalid prop `children` of type `string` supplied

    javascript - 检查是否用 Jest/ enzyme 检查复选框

    javascript - 创建 React App ,所有测试用例都因 1 个错误而失败

    jestjs - 开 Jest : how to mock a function which is used by another function of the same module

    reactjs - 开 Jest , enzyme : Invariant Violation: You should not use <Route> or withRouter() outside a <Router>

    typescript - 如何在 Jest 测试文件中使用从 typescript 文件导入模块

    javascript - 覆盖对象属性以进行单元测试