使用Jasmine监视document.createElement会从angular mock中抛出错误

时间:2016-02-12 18:21:52

标签: javascript angularjs unit-testing jasmine angular-mock

我有一个处理网络摄像头的Angular服务。以下是我试图测试的功能:

this.takePicture = function() {
    var canvas = document.createElement('canvas');
    canvas.width = this.width;
    canvas.height = this.height;

    var context = canvas.getContext('2d');
    context.drawImage(this.videoElement, 0, 0, this.width, this.height);

    return canvas.toDataURL('image/jpeg', 100);
};

我试图模拟对document.createElement的调用并返回一个假的canvas对象。这是我的测试:

it('should draw an image', function() {
    var drawImageSpy = jasmine.createSpy('drawImage');

    var canvas = {
        getContext: jasmine.createSpy('getContext').and.returnValue({ drawImage: drawImageSpy }),
        width: 0,
        height: 0,
        toDataURL: jasmine.createSpy('toDataUrl').and.returnValue('data-uri')
    };

    document.createElement = jasmine.createSpy('createCanvas').and.returnValue(canvas);

    WcCameraService.takePicture();

    expect(drawImageSpy).toHaveBeenCalled();
});

以下是我遇到的错误:

TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
    at TypeError (native)
    at Function.jQuery.extend.buildFragment (C:/Projects/Accurev/WebCOE_FRF_DEV/src/bower_components/jquery/dist/jquery.js:5565:24)
    at Function.jQuery.parseHTML (C:/Projects/Accurev/WebCOE_FRF_DEV/src/bower_components/jquery/dist/jquery.js:9923:18)
    at jQuery.fn.init (C:/Projects/Accurev/WebCOE_FRF_DEV/src/bower_components/jquery/dist/jquery.js:2774:33)
    at Object.jQuery [as element] (C:/Projects/Accurev/WebCOE_FRF_DEV/src/bower_components/jquery/dist/jquery.js:73:10)
    at $get (C:/Projects/Accurev/WebCOE_FRF_DEV/src/bower_components/angular-mocks/angular-mocks.min.js:6:18224)
    at Object.e [as invoke] (C:/Projects/Accurev/WebCOE_FRF_DEV/src/bower_components/angular/angular.min.js:39:193)
    at C:/Projects/Accurev/WebCOE_FRF_DEV/src/bower_components/angular/angular.min.js:41:10
    at Object.d [as get] (C:/Projects/Accurev/WebCOE_FRF_DEV/src/bower_components/angular/angular.min.js:38:394)
    at Object.<anonymous> (C:/Projects/Accurev/WebCOE_FRF_DEV/src/bower_components/angular-mocks/angular-mocks.min.js:6:21105)

有谁知道为什么会这样?我正在寻找角度模拟,现在似乎失败了:

if (window.jasmine || window.mocha) {

...

  if (injector) {
    injector.get('$rootElement').off();
  }

2 个答案:

答案 0 :(得分:0)

据我所知,document.createElement是不可变的。你真的不应该首先监视它。它是一个内置函数,每次都会以相同的方式执行。你的其他间谍看起来很好。

答案 1 :(得分:0)

对此进行监视很奇怪。但是-在更大版本的angular中-您可以通过监视createElement方法来实现。您可以将其与带有茉莉间谍的returnValue配合使用,以期待某些来电。像这样:

const toDataUrlSpy = jasmine.createSpy('dataUrl');
spyOn(document, 'createElement').and.returnValue({
  width: 0,
  height: '',
  getContext: () => ({ drawImage: () => {} })
  toDataURL: toDataUrlSpy
});

service.takePicture();
expect(toDataUrlSpy).toHaveBeenCalledTimes(1);

干杯!