Raa*_*esh 6 mocha.js node.js typescript
我有一个使用摩卡的打字稿项目。假设我们有两个模块,如下所示。
// http.ts
export class Http {
}
// app.ts
import Http from './http';
export class App {
}
Run Code Online (Sandbox Code Playgroud)
当我测试应用程序时,如何模拟 Http 模块?
测试是通过npm脚本执行的,如下所示。
"test": "cross-env NODE_ENV=test ./node_modules/mocha/bin/mocha",
Run Code Online (Sandbox Code Playgroud)
摩卡选项 (mocha.opts) 如下所示。
test/setup.ts
--compilers ts:ts-node/register
--compilers tsx:ts-node/register
./src/**/*.spec.ts
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
现在您可以控制 Http 模块在测试中的行为方式。
模拟对 get 的响应:
httpMock.mock('get', { data: true });
const response = app.makeGetRequest(); // returns { data: true }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7350 次 |
| 最近记录: |