[英]How spy whether a function has been used or not with Jest unit testing for javascript?
When I try to set a spy on a imported function I get the following error msg TypeError: Cannot read property '_isMockFunction' of undefined 当我尝试对导入的函数设置间谍时,出现以下错误消息msg TypeError:无法读取未定义的属性'_isMockFunction'
I don't understand what it's wrong with this code 我不明白这段代码有什么问题
Imported function is like below here export 导入功能如下图所示
export
function myFn(){
let htmlEl = document.querySelector('html');
let el = document.querySelector('.target-el');
if(el){
el.addEventListener('click', myInternalFn, false);
}
function myInternalFn () {
isUserLoggedIn((isIn) => {
let logoutClassName = 'el--logout';
if (isIn) {
el.classList.remove(logoutClassName);
return;
}
el.classList.add(logoutClassName);
});
}
function isUserLoggedIn (fn) {
return fn(localStorage.getItem('userLoggedIn') === 'true');
}
}
document.addEventListener('DOMContentLoaded', () => {
myFn();
});
TDD: TDD:
import { betSlip } from "../src/main/javascript/custom/betslip-dialog";
describe('Testing bet slip button (only on mobile)', function () {
let htmlEl;
let el;
beforeEach(() => {
document.body.innerHTML =
`
<html>
<div class="target-el"></div>
</html>
`;
myFn();
htmlEl = document.querySelector('html');
});
it('When el button has been clicked for the first time', done => {
jest.spyOn(myFn, 'myInternalFn');
myInternalFn.click();
expect(true).toBe(true);
done();
});
});
According to Jest docs https://facebook.github.io/jest/docs/en/jest-object.html#jestspyonobject-methodname in your code 根据Jest docs https://facebook.github.io/jest/docs/en/jest-object.html#jestspyonobject-methodname
jest.spyOn(myFn, 'myInternalFn');
myFn
needs to be an object and myInternalFn
needs to be a property of this object. myFn
必须是一个对象,而myInternalFn
必须是此对象的属性。 In current realization myInternalFn
is hidden in myFn
scope, and isn't exposed to outside. 在当前实现中, myInternalFn
隐藏在myFn
范围内,并且不暴露于外部。 I suggest you to rewrite code (if it's possible) to use either prototype: 我建议您重写代码(如果可能)以使用任何一个原型:
myFn.prototype.myInternalFn = function myInternalFn () { ... }
//and in tests
jest.spyOn(myFn.prototype, 'myInternalFn');
or direct assign to function object(not the best way as for me) 或直接分配给函数对象(对我来说不是最好的方法)
myFn.myInternalFn = function myInternalFn () { ... }
// and in tests
jest.spyOn(myFn, 'myInternalFn');
A main idea is - without public exposing myInternalFn
you can't hang spy on it. 一个主要的想法是-如果不公开暴露myInternalFn
您就无法对其进行监视。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.