node.js - 使用 Mocha 和 Typescript 模拟依赖关系

标签 node.js typescript mocha.js

我有一个使用 Mocha 的 typescript 项目。假设我们有两个模块,如下所示。

// 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

最佳答案

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 }

关于node.js - 使用 Mocha 和 Typescript 模拟依赖关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38016997/

相关文章:

node.js - 使用 grunt-mocha-test 创建测试组

node.js - 无法使用 sails 运行 mocha 测试

javascript - 如何在路由路径中添加 connect-multiparty?

node.js - 我无法使用 typescript 构建 docker image 错误

html - 使用 Gulp 在 html 页面中处理嵌入的 css

html - 无法在 typescript 中转换 HTMLSelectElement

javascript - 如何获取描述 block 中输入的描述? ( typescript )

javascript - 全局 BeforeEach 用于使用 Mocha 和 Angular 模拟 HTTP 请求

node.js - Helmet CSP 在 Safari 浏览器中不起作用

node.js - typescript express 中间件