javascript - 如何替换 Polymer 中的元素和 stub 方法

标签 javascript unit-testing testing polymer polymer-2.x

在我的单元测试中,我希望能够用模拟元素替换元素,并为原始元素的方法提供 stub 。

例如,假设我的组件模板是这样的:

<template>
   <my-other-element id="myOtherElement"></my-other-element>
</template>

让我们稍后在我的元素中做这样的事情:

myMethod: function () {
   this.$.myOtherElement.foo();
}

当我为我的元素编写单元测试时,我想执行以下操作:

  1. 模拟整个 <my-other-element>
  2. foo()提供 stub 方法

我找到了一种方法来实现这一点,但不知何故它似乎不是很干净。我目前的解决方案如下:

var fooStub;

beforeEach(function () {
    fooStub = sinon.stub();

    replace('my-other-element').with('fake-my-other-element');
    document.createElement('fake-my-other-element').constructor.prototype = {
        foo: fooStub
    };
    element = fixture('basic');
});  

我想知道是否有更好的方法可以达到同样的效果。以某种方式创建一个空元素以更改 prototype添加 stub 的属性似乎不是最好的方法。

我知道你也可以这样做:

stub('my-other-element', {
    foo: fooStub
});

但我更喜欢总是提前模拟所有内容,以确保没有来自子元素的副作用。

最佳答案

我使用了一些选项。一种是主动将这些方法添加到有问题的元素中

chai.should();
suite('let\s stub a child method', () => {
  let testView;
  setup(() => {
    replace('child-el').with('fake-child-el');
    testView = fixture('basic');
    testView.$.child.method = sinon.stub();
  });

  test('myMethod() calls child method', () => {
    testView.myMethod();
    testView.$.child.method.should.have.been.called;
  });
});

另一个是创建一个假元素来 stub 并包装它的方法

Polymer({is: 'fake-child-el', method: sinon.stub;});

chai.should();
suite('let\s stub a child method', () => {
  let testView;
  setup(() => {
    replace('child-el').with('fake-child-el');
    testView = fixture('basic');
  });

  test('myMethod() calls child method', () => {
    testView.myMethod();
    testView.$.child.method.should.have.been.called;
  });
});

这可能不适用于所有浏览器。

编辑:在第二种方法失败的情况下,我已经使 stub 元素的方法类似于 method: () => null,然后将该方法包装在 sinon.stub( ) 在测试套件中调用。

关于javascript - 如何替换 Polymer 中的元素和 stub 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45564106/

相关文章:

javascript - 使用 replace() 替换过多的内容

javascript - $ ('<div>' ) 和 $ ('<div/>' ) 之间的区别

javascript - Jasmine : mocking $animate from Angular Material

java - 在 AndroidTestCase 中调用 MockitoAnnotations.initMocks() 时的 NPE

javascript - 无法读取未定义的属性 'use_env_variable'

javascript - android: webview 不使用自定义 WebViewClient 加载 javascript

javascript - Puppeteer,保存网页和图片

c++ - 在现有项目中创建 CPPUnit 测试需要哪些 .cpp 和 .h 文件?

unit-testing - 单元测试控制台输出

unit-testing - 学习编写单元测试