您不能模拟 onSuccess 函数。它是在功能范围内定义的,它是私有的。 如果你不能访问它,你就不能模拟或窥探它。
您可以监视console.log 方法。如果被调用,则间接表示调用了onSuccess。只是console.log 没有多大意义,这只是一个演示。
例如
index.tsx:
//@ts-nocheck
import React from 'react';
import { useEffect } from 'react';
export default function ReCaptcha() {
function onSuccess() {
console.log('we are sucessful');
}
useEffect(() => {
window.grecaptcha = {
enterprise: {},
};
window.grecaptcha.enterprise = {
execute: function () {
return new Promise((resolve) => {
resolve();
});
},
};
window.grecaptcha.enterprise.execute().then(() => {
onSuccess();
});
}, []);
return <h1>ReCaptcha</h1>;
}
index.test.tsx:
import { render, waitFor } from '@testing-library/react';
import React from 'react';
import ReCaptcha from './';
describe('ReCaptcha', () => {
test('should pass', async () => {
const logSpy = jest.spyOn(console, 'log');
render(<ReCaptcha />);
await waitFor(() => expect(logSpy).toBeCalledWith('we are sucessful'));
});
});
测试结果:
PASS examples/70457908/index.test.tsx (10.199 s)
ReCaptcha
✓ should pass (75 ms)
console.log
we are sucessful
at console.<anonymous> (node_modules/jest-mock/build/index.js:845:25)
-----------|---------|----------|---------|---------|-------------------
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: 11.334 s