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

使用Jest测试TypeScript类静态方法的正确性及导入方法咨询

Hey there! Let's fix up your Jest test for the getProjectBranch static method and get it working properly.

First: How to Import the Method

Since getProjectBranch is a static method on the TotoService class, you'll need to import the class from your totoService.ts file first. Assuming your test file is in the same directory as the service, add this import at the top of totoService.spec.ts:

import { TotoService } from './totoService';

If you prefer to import just the static method directly (though importing the class is more explicit for static methods), you can do this too:

import { getProjectBranch } from './totoService';

Just make sure your totoService.ts exports the class properly—for example, your service file should have something like:

export class TotoService {
  public static getProjectBranch(toto: any): string {
    if ("branch" in toto) {
      return toto.branch;
    } else {
      return "master";
    }
  }
}

Second: Fixing Your Test Code

Your current test has a couple of issues that will cause it to fail:

  1. You're calling getProjectBranch() without passing the required toto parameter
  2. You're expecting an empty string "" as the result, which doesn't match the logic of your method
  3. You're only testing one scenario, but your method has two paths (branch exists / doesn't exist)

Here's the corrected test code that covers both cases:

describe("Test getProjectBranch method", () => {
  test("returns the provided branch when 'branch' property exists in toto", () => {
    // Create a test object with a branch property
    const testTotoWithBranch = { branch: "feature/user-profile" };
    expect(TotoService.getProjectBranch(testTotoWithBranch)).toBe("feature/user-profile");
  });

  test("returns 'master' when 'branch' property does not exist in toto", () => {
    // Test with an object that has no branch
    const testTotoWithoutBranch = { id: 123, name: "Test Project" };
    expect(TotoService.getProjectBranch(testTotoWithoutBranch)).toBe("master");

    // Also test with an empty object to cover that edge case
    expect(TotoService.getProjectBranch({})).toBe("master");
  });
});

What this fixes:

  • We're now passing a valid toto object to the method in each test
  • We're expecting results that match your method's logic (the branch value when present, "master" otherwise)
  • We're covering both code paths in your method to ensure it works as intended in all scenarios

内容的提问来源于stack exchange,提问作者ffzefzef zefzeff

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 16:37:37