You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

  1. 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. The jest.fn().mockReturnValue(samplePolicy) line creates a brand new, unrelated mock function instead of modifying the one tied to your module.
  2. Ignoring async function behavior: Your getBucketPolicyJson is an async function (returns a Promise), so you need to mock a resolved Promise instead of returning a raw value directly. Using mockReturnValue here would pass a non-Promise value, which can lead to unexpected behavior when awaited in getPolicy.

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 calling mockResolvedValue on it, you're updating the actual function that getPolicy will call.
  • Using mockResolvedValue: This ensures the mock returns a resolved Promise, matching the async behavior of the original getBucketPolicyJson function. await in getPolicy will correctly unwrap this Promise to get your sample policy.
  • Type safety: The as jest.Mock assertion tells TypeScript that we're working with a Jest mock function, allowing us to use mock-specific methods like mockResolvedValue.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 15:57:33