jQuery jest.fn() 值必须是模拟函数或间谍
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44525729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jest.fn() value must be a mock function or spy
提问by me-me
I have a function in a module called button-actions that is called when a user clicks a back button. I want to test the backButtonActions method directly but need to mock up the leaveApp and displayById methods inside backButtonActions that get called.
我在名为 button-actions 的模块中有一个函数,当用户单击后退按钮时会调用该函数。我想直接测试 backButtonActions 方法,但需要模拟被调用的 backButtonActions 中的 leaveApp 和 displayById 方法。
Here is my button-actions.jsfile method.
这是我的button-actions.js文件方法。
export function backButtonActions( label, page ){ //, page
console.log("LABEL = ", label, " page = ", page);
switch( label ){
case 'step1':
page.leaveApp();
break;
case 'step2':
page.displayById();
break;
}
}
I'm new to tests so I might be missing something very simple. Below is my test.jsfile
我是测试新手,所以我可能会遗漏一些非常简单的东西。下面是我的test.js文件
window.$ = require('jquery');
import {backButtonActions} from '../button-actions';
describe('Button Actions', () => {
const page = {}
beforeEach(() => {
page.leaveApp = jest.fn(() => "leave");
page.displayById = jest.fn(() => "Display");
document.body.innerHTML =
'<div>' +
' <button class="btn-back" />' +
'</div>';
$('.btn-back').click((event, label) =>{
backButtonActions( label, page );
});
});
it('backButtonActions requires a string of either "step1" or "step2"', () => {
$('.btn-back').trigger('click', 'step1');
expect(backButtonActions).toBeCalled();
expect(backButtonActions).toBeCalledWith("step1" || "step2");
});
})
When I run the above test I get the following error.
当我运行上述测试时,出现以下错误。
● Button Actions ? backButtonActions requires a string of either "step 1" or "step 2"
expect(jest.fn())[.not].toBeCalled() jest.fn() value must be a mock function or spy. Received: function: [Function backButtonActions] at Object.<anonymous> (test/js/spec/create/button-actions.test.js:64:50)
● 按钮操作?backButtonActions 需要字符串“step 1”或“step 2”
expect(jest.fn())[.not].toBeCalled() jest.fn() value must be a mock function or spy. Received: function: [Function backButtonActions] at Object.<anonymous> (test/js/spec/create/button-actions.test.js:64:50)
Is there something else I should be running to get this to work ?
还有什么我应该运行才能让它工作吗?
采纳答案by Mike Bell
You need to spy on the backButtonActions
function, either via jasmine's spyOn
method or via Jest's jest.spyOn
method
您需要backButtonActions
通过 jasmine 的spyOn
方法或 Jest 的jest.spyOn
方法监视该函数
https://facebook.github.io/jest/docs/jest-object.html#jestspyonobject-methodname
https://facebook.github.io/jest/docs/jest-object.html#jestspyonobject-methodname