我正在对项目添加测试并提高覆盖范围。我想知道如何在 NestJs 中测试模块定义(mymodule.module.ts 文件)。特别是,我正在测试一个导入其他模块的主模块,其中一个模块初始化数据库连接,这意味着我需要模拟另一个模块上的服务,以避免真正的数据库连接。此时此刻我有这样的事情:
beforeEach(async () => {
const instance: express.Application = express();
module = await NestFactory.create(MyModule, instance);
});
describe('module bootstrap', () => {
it('should initialize entities successfully', async () => {
controller = module.get(MyController);
...
expect(controller instanceof MyController).toBeTruthy();
});
});
Run Code Online (Sandbox Code Playgroud)
这可行,但我相信这可以得到改进:)
理想的情况是 Test.createTestingModule 提供的 overrideComponent 方法。
PS:我使用的是4.5.2版本
根据 @laurent-thiebault 的回答改进了我的测试:
import { Test } from '@nestjs/testing';
import { ThingsModule } from './things.module';
import { ThingsResolver } from './things.resolver';
import { ThingsService } from './things.service';
describe('ThingsModule', () => {
it('should compile the module', async () => {
const module = await Test.createTestingModule({
imports: [ThingsModule],
}).compile();
expect(module).toBeDefined();
expect(module.get(ThingsResolver)).toBeInstanceOf(ThingsResolver);
expect(module.get(ThingsService)).toBeInstanceOf(ThingsService);
});
});
Run Code Online (Sandbox Code Playgroud)
您现在可以通过这种方式构建来测试您的模块(至少是代码覆盖率):
describe('MyController', () => {
let myController: MyController;
beforeEach(async () => {
const module = await Test.createTestingModule({
imports: [MyModule],
}).compile();
myController = module.get<MyController>(MyController);
});
it('should the correct value', () => {
expect(myController.<...>).toEqual(<...>);
});
});
Run Code Online (Sandbox Code Playgroud)
我们通常不.module.ts
直接测试文件。
我们在e2e
测试中这样做。
但我想知道why one should test the the module !
您正在尝试测试模块是否可以初始化其组件,它应该。
但我建议你在e2e
测试中这样做。在我看来,在单元测试中,您应该专注于测试服务或其他组件行为而不是模块。
归档时间: |
|
查看次数: |
18903 次 |
最近记录: |