使用 Bazel 自定义规则在 Typescript 中使用 Jest 进行测试

Cra*_*zit 5 typescript jestjs bazel

我正在尝试使用 Jest 和 Bazel 来测试我的 Typescript 代码。

的 repo上有一个示例rules_nodejs,但它只是使用原始 Javascript 文件:https ://github.com/bazelbuild/rules_nodejs/tree/master/examples/jest

我的目标是使用ts_library规则(来自)编译我的 Typescript 代码,然后将其传递给 Jest 规则(我对 Jest 使用与的存储库rules_nodejs示例中相同的规则)。rules_nodejs

这是玩笑规则:

# //:rules/jest.bzl

load("@npm//jest-cli:index.bzl", _jest_test = "jest_test")

def jest_test(name, srcs, deps, jest_config, **kwargs):
    "A macro around the autogenerated jest_test rule"
    args = [
        "--no-cache",
        "--no-watchman",
        "--ci",
    ]
    args.extend(["--config", "$(location %s)" % jest_config])

    for src in srcs:
        args.extend(["--runTestsByPath", "$(locations %s)" % src])

    _jest_test(
        name = name,
        data = [jest_config] + srcs + deps,
        args = args,
        **kwargs
    )
Run Code Online (Sandbox Code Playgroud)

我的构建文件位于src

# //:src/BUILD.bazel

load("@npm_bazel_typescript//:index.bzl", "ts_library")
load("//:rules/jest.bzl", "jest_test")

ts_library(
    name = "src",
    srcs = glob(["*.ts"]),
    deps = [
        "@npm//:node_modules"
    ]
)

jest_test(
    name = "test",
    srcs = [":src"],
    jest_config = "//:jest.config.js",
    tags = [
        # Need to set the pwd to avoid jest needing a runfiles helper
        # Windows users with permissions can use --enable_runfiles
        # to make this test work
        "no-bazelci-windows",
    ],
    deps = [
        "@npm//:node_modules"
    ],
)
Run Code Online (Sandbox Code Playgroud)

我还从示例中获取了 Jest 配置:

// //:jest.config.js

module.exports = {
  testEnvironment: "node",

  transform: { "^.+\\.jsx?$": "babel-jest" },
  testMatch: ["**/*.test.js"]
};
Run Code Online (Sandbox Code Playgroud)

我要测试的文件:

// //:src/foo.test.ts

test("It can test", () => {
  expect(2).toEqual(2);
});
Run Code Online (Sandbox Code Playgroud)

毕竟,当我跑步时,bazel run //src:test我得到:

Executing tests from //src:test
-----------------------------------------------------------------------------
No tests found, exiting with code 1
Run with `--passWithNoTests` to exit with code 0
No files found in /home/anatole/.cache/bazel/_bazel_anatole/8d84caec5a0442239ce878a70e921a6b/execroot/examples_app/bazel-out/k8-fastbuild/bin/src/test.sh.runfiles/examples_app.
Make sure Jest's configuration does not exclude this directory.
To set up Jest, make sure a package.json file exists.
Jest Documentation: facebook.github.io/jest/docs/configuration.html
Files: "src/foo.test.d.ts"
Run Code Online (Sandbox Code Playgroud)

根据错误的最后一行,似乎 Jest 规则只获取文件.d.ts(我不知道为什么)。

ant*_*_Ti 5

看来您需要从ts_library. 这可以通过以下方式实现filegroup

ts_library(
    name = "src",
    ...
)

filegroup(
    name = "js_src",
    srcs = [":src"],
    output_group = "es5_sources",
)

jest_test(
    name = "test",
    srcs = [":js_src"],
    ...
)

Run Code Online (Sandbox Code Playgroud)

有关此内容的更多信息可以在文档的访问 JavaScript 输出部分中找到rules_typescript