TypeScript中使用Jest模拟依赖模块getBucketPolicyJson以测试getPolicy函数的问题排查
Jest Mock Not Working for Async Function in Test Case
Let's break down where your test setup is going wrong and how to fix it:
The Core Issues
- You're not linking your mock to the actual module export: When you call
jest.mock('../modules/getbucketpolicyjson'), Jest automatically creates a mock version of all exports from that module—but you never updated that auto-generated mock with your sample policy. Thejest.fn().mockReturnValue(samplePolicy)line creates a brand new, unrelated mock function instead of modifying the one tied to your module. - Ignoring async function behavior: Your
getBucketPolicyJsonis an async function (returns a Promise), so you need to mock a resolved Promise instead of returning a raw value directly. UsingmockReturnValuehere would pass a non-Promise value, which can lead to unexpected behavior whenawaited ingetPolicy.
Fixed Test Code
Here's the corrected approach with explanations:
// Import your target function and the mocked module's export import { getPolicy } from './path-to-your-getPolicy-module'; import { getBucketPolicyJson } from '../modules/getbucketpolicyjson'; import { Policy } from '../types'; // Initialize the mock for the module (this stays the same) jest.mock('../modules/getbucketpolicyjson'); describe('getPolicy', () => { it('should return a Policy object when getBucketPolicyJson succeeds', async () => { // Define your sample policy const samplePolicy: Policy = { 'Version': '01', 'Id': '1', 'Statement': [] }; // Update the auto-generated mock function to return a resolved Promise // We use type assertion here because Jest mocks aren't typed by default (getBucketPolicyJson as jest.Mock).mockResolvedValue(samplePolicy); // Run your test const res = await getPolicy('test-buck-policy'); console.log("response ", res); // This will now log your samplePolicy // Add assertions to validate behavior expect(res).toEqual(samplePolicy); expect(getBucketPolicyJson).toHaveBeenCalledExactlyOnceWith('test-buck-policy'); }); });
Key Fixes Explained
- Linking the mock to the module: By referencing
getBucketPolicyJson(the exported mock from the module) and callingmockResolvedValueon it, you're updating the actual function thatgetPolicywill call. - Using
mockResolvedValue: This ensures the mock returns a resolved Promise, matching the async behavior of the originalgetBucketPolicyJsonfunction.awaitingetPolicywill correctly unwrap this Promise to get your sample policy. - Type safety: The
as jest.Mockassertion tells TypeScript that we're working with a Jest mock function, allowing us to use mock-specific methods likemockResolvedValue.
Bonus: Testing the Error Scenario (For Reference)
Since you mentioned you already have this working, here's how you'd explicitly mock a failure to validate getPolicy returns false:
it('should return false when getBucketPolicyJson fails', async () => { (getBucketPolicyJson as jest.Mock).mockRejectedValue(new Error('Mock error')); const res = await getPolicy('failed-bucket'); expect(res).toBe(false); });
内容的提问来源于stack exchange,提问作者Steve
相关产品推荐
相关产品推荐

