【问题标题】:Jasmine spyOn javascript getter causing karma to hangJasmine spyOn javascript getter 导致业力挂起
【发布时间】:2015-07-10 10:12:00
【问题描述】:

我在使用 Jasmine 编写监视 Javascript getter 的测试时遇到了一些问题。它导致我的测试套件挂起(使用 karma + phantomJS),然后最终浏览器断开连接,并且从未比所讨论的测试更进一步。

一个简单的例子可能是最容易解释的方法(使用 ES6 与 webpack + babel-loader 转译):

class ExampleClass {
    get name() {
        return "My Name";
    }
}

为了更改此 get 方法为我的测试返回的内容,我正在尝试以下操作:

describe("example class getter"), function() {
    it("should return blue", function() {
        let exampleClass = new ExampleClass();
        spyOn(exampleClass, 'name').and.returnValue('blue');
        expect(exampleClass.name).toBe('blue');
    });
});

这会导致以下结果(相关测试是我的第 7 次测试):

PhantomJS 1.9.8 (Mac OS X 0.0.0): Executed 6 of 8 SUCCESS (0 secs / 0.02 secs)
WARN [PhantomJS 1.9.8 (Mac OS X 0.0.0)]: Disconnected (1 times), because no message in 10000 ms.
PhantomJS 1.9.8 (Mac OS X 0.0.0): Executed 6 of 8 DISCONNECTED (10.003 secs / 0.02 secs)
DEBUG [karma]: Run complete, exiting.

spyOn 适用于未使用 get 语法定义的其他方法,因此我确信用于编译的构建管道运行良好。

有没有人见过这个,或者对修复有任何想法?

【问题讨论】:

  • 如果您使用的是 Jasmine 2,.andReturn(value) 已更改为 .and.returnValue(value)
  • 非常正确,我在输入此示例时错过了这一点。不幸的是,这并不能解决问题,但我会更新问题以获得正确的代码,谢谢。
  • 呃,使用 getter 的属性不是方法。只是exampleClass.name === "My Name"。没有函数,没有可见的返回值。
  • 另外,我在某处缺少let exampleClass = new ExampleClass
  • let exampleClass = new ExampleClass is missing 因为我只是突出代码中的相关块,它在我的实际文件中更高。因此,鉴于 getter 不被视为方法,我认为这实际上是不可能的,我必须将方法更改为 getName()(虽然我已经充实了代码,但不应该在提问)

标签: javascript jasmine ecmascript-6


【解决方案1】:

我也一样。这是我解决这个问题的方法:

class Foo {
  get status() {
    return 0;
  }
}

所以模拟这个 Foo 进行测试:

class FooMock extends Foo {
  _fakeStatus() {
    return 1;
  }

  get status() {
    return this._fakeStatus();
  }
}

然后你使用FooMock 而不是Foo!例如:

it('check the status', () => {
  spyOn(fooInstance, '_fakeStatus').and.returnValue(3);
  expect(fooInstance.status).toBe(3);
}

希望这对你有用! :)

【讨论】:

    【解决方案2】:

    我认为您在 expect 调用中忽略了调用 name 函数。像这样:

    describe("example class getter"), function() {
        it("should return blue", function() {
            let exampleClass = new ExampleClass();
            spyOn(exampleClass, 'name').and.returnValue('blue');
            expect(exampleClass.name()).toBe('blue');
        });
    });
    

    【讨论】:

      猜你喜欢
      • 2023-03-16
      • 2015-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-24
      • 1970-01-01
      相关资源
      最近更新 更多