【问题标题】:Mock dependencies with Mocha and Typescript使用 Mocha 和 Typescript 模拟依赖项
【发布时间】:2016-10-27 06:51:33
【问题描述】:

我有一个使用 mocha 的打字稿项目。假设我们有如下两个模块。

// http.ts
export class Http {
}

// app.ts
import Http from './http';

export class App {

}

我在测试应用程序时如何模拟 Http 模块?

测试通过如下的 npm 脚本执行。

"test": "cross-env NODE_ENV=test ./node_modules/mocha/bin/mocha",

mocha 选项 (mocha.opts) 如下所示。

test/setup.ts
--compilers ts:ts-node/register
--compilers tsx:ts-node/register
./src/**/*.spec.ts

【问题讨论】:

    标签: node.js typescript mocha.js


    【解决方案1】:

    ts-mock-imports 让您可以在运行时控制导入并保持类型安全。

    app.spec.ts

    import * as httpModule from 'http';
    import { App } from '../src/app';
    import { ImportMock } from 'ts-mock-imports';
    
    const httpMock = ImportMock.mockClass(httpModule, 'Http');
    
    const app = new App(); // App now uses a fake version of the Http class
    

    现在您可以控制 Http 模块在测试中的行为方式。

    模拟对 get 的响应:

    httpMock.mock('get', { data: true });
    
    const response = app.makeGetRequest(); // returns { data: true }
    

    【讨论】:

      【解决方案2】:

      typescript 中的import 语句编译为require。您可以使用proxyquire 模拟测试中的任何依赖项

      【讨论】:

      • 我也无法使用 proxyquire。我最终将 webpack 与 inject-loader 一起使用。
      • @Raathigesh 你介意分享你的发现吗?我正在努力实现同样的目标..
      • @AndyPerlitch 我最终使用了 webpack 和 Inject-loader (github.com/plasticine/inject-loader)
      • 我创建了 ts-mock-imports 以在 typescript 环境中像 proxyquire 一样工作。
      • 回顾我的回答,我今天会做不同的事情。从长远来看,使用 Inversify 之类的东西将模拟依赖项注入测试会更容易。
      猜你喜欢
      • 2020-12-03
      • 1970-01-01
      • 2016-04-22
      • 1970-01-01
      • 2018-07-23
      • 1970-01-01
      • 2020-12-09
      • 2014-09-23
      • 2023-03-12
      相关资源
      最近更新 更多