> For AI agents: the complete documentation index is available at /zh/llms.txt, the full documentation bundle is available at /zh/llms-full.txt.

# includeSource

- **类型：** `string[]`
- **默认值：** `[]`

源码内联测试（In-source testing）指的是测试代码与源代码写在同一个文件中，类似于 [Rust 的模块测试](https://doc.rust-lang.org/book/ch11-03-test-organization.html#the-tests-module-and-cfgtest)。

你可以通过 `includeSource` 配置，定义一组用于匹配内联测试文件的 glob 模式列表。

```ts
import { defineConfig } from '@rstest/core';

export default defineConfig({
  includeSource: ['src/**/*.{js,ts}'],
});
```

:::tip
源码内联测试通常适用于小型功能函数和工具方法，能够方便地进行快速验证和调试。对于更复杂的功能和模块，建议使用独立的测试文件。
:::

`includeSource` 同时适用于 Node 模式与[浏览器模式](/zh/guide/browser-testing.md)项目。

### 编写内联测试

当定义了 `includeSource` 后，Rstest 会运行所有通过 glob 匹配且包含 `import.meta.rstest` 的文件。

你可以通过 `import.meta.rstest` 获取 Rstest 的测试 API。

```ts title=src/helper.ts
export const sayHi = () => 'hi';

if (import.meta.rstest) {
  const { it, expect } = import.meta.rstest;
  it('should test source code correctly', () => {
    expect(sayHi()).toBe('hi');
  });
}
```

### 生产环境构建

将测试代码写在 `if (import.meta.rstest)` 代码块内。生成非测试产物时，请在项目的构建配置中将 `import.meta.rstest` 定义为 `false`，这样打包工具就能将测试代码作为无用代码移除。

- 使用 Rspack 的 [DefinePlugin](https://rspack.rs/zh/plugins/webpack/define-plugin)：

```diff title=rspack.config.ts
import { defineConfig } from '@rspack/cli';
+import { rspack } from '@rspack/core';

export default defineConfig({
+  plugins: [
+    new rspack.DefinePlugin({
+      'import.meta.rstest': false,
+    }),
+  ],
});
```

- 使用 Rsbuild 的 [source.define](https://rsbuild.rs/zh/config/source/define) 选项：

```diff title=rsbuild.config.ts
import { defineConfig } from '@rsbuild/core';

export default defineConfig({
  source: {
    define: {
+      'import.meta.rstest': false,
    },
  },
});
```

### TypeScript

如需让 TypeScript 支持 `import.meta.rstest`，推荐在测试文件对应的 `tsconfig.json` 中，将 `@rstest/core/importMeta` 添加到 `compilerOptions.types`：

```json title=tsconfig.json
{
  "compilerOptions": {
    "types": ["@rstest/core/importMeta"]
  }
}
```

> 如果已有 `compilerOptions.types` 配置，请将该类型追加到现有列表中。

也可以在 `src/rstestEnv.d.ts` 中引用类型：

```ts title=rstestEnv.d.ts
/// <reference types="@rstest/core/importMeta" />
```
