javascript - javascript 类的单元测试 (ES6) - stub 不起作用

标签 javascript node.js unit-testing

我在 javascript (react) 项目中遇到单元测试问题。 想要测试 ApiClient 类。为此,我必须隔离 settingsApi、HttpClient 和资源。 我使用的工具:mocha、chai、sinon

我也尝试过使用重新接线,但不行。我已经读到这可能是因为 babel。

我尝试过这样的 stub :

sinon.stub(ApiClient.prototype, 'constructor');

有人遇到过这个问题吗,可以帮我一下吗?

下面是部分代码:

文件 ApiClient.js

import settingsApi from '../../settings/api.json';
import HttpClient from './HttpClient';
import resources from './resources';

class ApiClient {
  constructor() {
    this.httpClient = new HttpClient(settingsApi);
  }

  get flux() {
    return new resources.resourceOne(this.httpClient);
  }
}

export default ApiClient;

FileHttpClient.js

class HttpClient {
/**
 * 
 * @param {*} config 
 */
constructor(config) {
    this.basePath = `${config.protocol}://${config.host}:${config.port}`;
}

post(resource, options = {}, formatResponse) {
    return this.request({
        method: 'POST',
        resource,
        options,
        formatResponse
    });
}


export default HttpClient;

最佳答案

我已经可以解决我的问题了,我使用了 babel-plugin-rewire ( https://github.com/speedskater/babel-plugin-rewire ):

安装:

yarn add babel-core babel-plugin-rewire --dev

添加到.babelrc

"plugins": [
    "rewire"
]

模拟依赖项示例:

ApiClient.__Rewire__('settingsApi', {
  paramConfig: 'config',
});

ApiClient.__Rewire__('HttpClient', class HttpClient {
    constructor(config) {
    }
});

ApiClient.__Rewire__('resources', {
    resourceOne: class {
       constructor(httpClient) {       
       }
});

现在不再调用依赖项,而是调用上述函数。

关于javascript - javascript 类的单元测试 (ES6) - stub 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51305249/

相关文章:

unit-testing - Resharper单元测试运行器无法在发行版中运行测试(System.BadImageFormatException)

ruby-on-rails - 如何使固定装置在 Rails 的测试中可更新?

unit-testing - Go 单元测试中的自定义命令行标志

JavaScript,循环所有选择?

javascript - 在 Javascript 中启用 ASP 隐藏标签

javascript - IE中的ContextMenu获取当前打开的浏览器url

javascript - 带有 TypeScript 的函数名称的 ESlint 规则(驼峰式,首字母小写)

javascript - 如果原始 src 无法加载内容且超时,iframe 使用替代图像

css - NodeJS 看不到 LESS,尽管它是使用全局选项安装的

javascript - 验证 google reCaptcha 时输入响应和密码无效