我正在尝试监视reactJS功能组件内的函数。我已经看到了一些答案,并了解了我们将函数作为 props 传递给组件的过程。但这个方法对我来说不起作用。所以我尝试使用
const spy = jest.spyOn(App.prototype, "sampleFunctionName");
正如预期的那样,它会抛出一个错误,指出 sampleFunctionName
未定义,因为 App.prototype 不包含它。因此,为了克服这个问题,我将 sampleFunctionName
添加到 App.prototype 作为 App.prototype.sampleFunctionName = jest.fn()
并尝试将其监视为
wrapper = shallow(<App {...props} />);
wrapper.find("#btn-id").simulate("click")
expect(spy).toHaveBeenCalled()
现在的问题是调用spy的次数始终为零。所以我想知道我所尝试的方法是否正确,或者是否有其他方法可以在无类组件中监视函数
下面是一个演示上述要求的示例:
function App(props){
function save(){
//contains the code for api calls and store changes
}
return(
<Button id = "btn-id" onClick = {save}>Name</Button>
)
}
测试文件如下:
import React from "react";
import { shallow } from "enzyme";
import {App} from './App'
describe('desc',() =>{
...
const spy = jest.spyOn(App.prototype, "save");
//using the above spy says "save" is undefined so added this line before using spy
// App.prototype.save = jest.fn()
wrapper = shallow(<App {...props} />);
wrapper.find("#btn-id").simulate("click")
expect(spy).toHaveBeenCalled()
})
最佳答案
您无法模拟或监视 save
函数,它是 App
构造函数中的私有(private)函数,不是 App 实例的方法,这意味着App原型(prototype)中不存在save
函数。您应该模拟或监视 save
函数内的函数,即针对您的情况进行 api 调用的函数/方法。这是单元测试解决方案:
例如
index.js
:
import React from 'react';
export function App(props) {
function save() {
// contains the code for api calls and store changes
console.log('You should spy or mock the function which make the api calls');
}
return (
<button id="btn-id" onClick={save}>
Name
</button>
);
}
index.test.js
:
import React from 'react';
import { shallow } from 'enzyme';
import { App } from './';
describe('61174416', () => {
it('should pass', () => {
const logSpy = jest.spyOn(console, 'log');
const props = {};
const wrapper = shallow(<App {...props} />);
wrapper.find('#btn-id').simulate('click');
expect(logSpy).toHaveBeenCalled();
});
});
100%覆盖率的单元测试结果:
PASS stackoverflow/61174416/index.test.tsx (8.332s)
61174416
✓ should pass (19ms)
console.log node_modules/jest-environment-enzyme/node_modules/jest-mock/build/index.js:866
You should spy or mock the function which make the api calls
-----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
index.tsx | 100 | 100 | 100 | 100 |
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 9.395s
将 console.log
替换为进行 api 调用的函数或方法。
源代码:https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/61174416
关于javascript - Reactjs 功能组件中的 Jest SpyOn,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61174416/