繁体   English   中英

如何使用带有参数的 Jest 模拟函数?

[英]How to mock a function using Jest that has parameters in it?

我有一个方法add ,我想模拟它:

js

function add(a, b, c) {
  return a + b + c
}

export add;

我像这样在componentDidMount调用这个add方法

js

import add from './A';

class AddForm extends React.Component {
    ...
    componentDidMount() {
       add(1, 2, 3);
    }
    ...
}

export AddForm;

现在这就是我测试它的方式

B.test.js

import AddForm from './B';

const helpers = require("./A");
jest.spyOn(helpers, "add").mockImplementation(() => 100);

describe('<AddForm/>', () => {
  test('should render all elements', () => {
     return render(
      <AddForm></AddForm>,
     );
  }
}

我在测试时没有得到模拟值100 ,而是执行了函数。 我尝试了所有可用的答案,但无法得到这个模拟响应。

我在这里缺少什么吗?

检查这些文件

样本:

const helpers = require("./A");
jest.mock('./A')
test('should render all elements', () => {
  helper.add.mockReturnValue(100);
  // write your test case
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM