मेरे पास मेरे कार्यों में एक कोशिश/पकड़ ब्लॉक है जिसे मैं परीक्षण करना चाहता हूं। दोनों फ़ंक्शन समान execute
फ़ंक्शन को कॉल करते हैं और यदि यह कोई त्रुटि फेंकता है तो वह पकड़ लेगा। मेरे परीक्षण सेटअप हैं जहां मैं शीर्ष के पास मॉड्यूल का मज़ाक उड़ा रहा हूं, और फिर मैं सत्यापित कर सकता हूं कि जेस्ट फ़ंक्शन को कितनी बार कहा जाता है।
जो मुझे समझ में नहीं आ रहा है वह यह है कि दूसरे परीक्षण में त्रुटि को बल execute
कैसे फेंका जाए, और फिर डिफ़ॉल्ट नकली कार्यान्वयन पर वापस जाएं। मैंने व्यक्तिगत परीक्षण में jest.mock को फिर से असाइन करने का प्रयास किया है लेकिन यह काम नहीं कर रहा है।
import {execute} from '../src/execute'
jest.mock('../src/execute', () => ({
execute: jest.fn()
}))
describe('git', () => {
afterEach(() => {
Object.assign(action, JSON.parse(originalAction))
})
describe('init', () => {
it('should stash changes if preserve is true', async () => {
Object.assign(action, {
silent: false,
accessToken: '123',
branch: 'branch',
folder: '.',
preserve: true,
isTest: true,
pusher: {
name: 'asd',
email: 'as@cat'
}
})
await init(action)
expect(execute).toBeCalledTimes(7)
})
})
describe('generateBranch', () => {
it('should execute six commands', async () => {
jest.mock('../src/execute', () => ({
execute: jest.fn().mockImplementation(() => {
throw new Error('throwing here so. I can ensure the error parsed properly');
});
}))
Object.assign(action, {
silent: false,
accessToken: '123',
branch: 'branch',
folder: '.',
pusher: {
name: 'asd',
email: 'as@cat'
}
})
// With how this is setup this should fail but its passing as execute is not throwing an error
await generateBranch(action)
expect(execute).toBeCalledTimes(6)
})
})
})
किसी भी सहायता की सराहना की जाएगी!
1 उत्तर
jest.mock
में should execute six commands
, ../src/execute
मॉड्यूल को प्रभावित नहीं करता है क्योंकि इसे पहले ही शीर्ष स्तर पर आयात किया जा चुका है।
jest.mock
शीर्ष स्तर पर पहले से ही जेस्ट जासूस के साथ execute
का मजाक उड़ाता है। अन्य परीक्षणों को प्रभावित न करने के लिए Once
कार्यान्वयन का उपयोग करना बेहतर है:
it('should execute six commands', async () => {
execute.mockImplementationOnce(() => {
throw new Error('throwing here so. I can ensure the error parsed properly');
});
...
इसके अलावा नकली को ES मॉड्यूल होने के लिए मजबूर किया जाना चाहिए क्योंकि execute
को आयात नाम दिया गया है:
jest.mock('../src/execute', () => ({
__esModule: true,
execute: jest.fn()
}))