1

保存時に backbone.model をテストしようとしています。
これが私のコードです。
コメントからわかるように、toHaveBeenCalledOnceメソッドに問題があります。

PS:
私は jasmine 1.2.0 と Sinon.JS 1.3.4 を使用しています。

    describe('when saving', function ()
    {
        beforeEach(function () {
            this.server = sinon.fakeServer.create();
            this.responseBody = '{"id":3,"title":"Hello","tags":["garden","weekend"]}';
            this.server.respondWith(
                'POST',
                Routing.generate(this.apiName),
                [
                    200, {'Content-Type': 'application/json'}, this.responseBody
                ]
            );
            this.eventSpy = sinon.spy();
        });

        afterEach(function() {
            this.server.restore();
        });

        it('should not save when title is empty', function() {
            this.model.bind('error', this.eventSpy);
            this.model.save({'title': ''});

            expect(this.eventSpy).toHaveBeenCalledOnce(); // TypeError: Object [object Object] has no method 'toHaveBeenCalledOnce'
            expect(this.eventSpy).toHaveBeenCalledWith(this.model, 'cannot have an empty title');
        });
    });

console.log(expect(this.eventSpy));

アスダス

4

3 に答える 3

2

ジャスミンには機能がありませんtoHaveBeenCalledOnce。カウントは自分で確認する必要があります。

expect(this.eventSpy).toHaveBeenCalled();
expect(this.eventSpy.callCount).toBe(1);

だから私はあなたの場合、あなたはこれが欲しいと思います:

expect(this.eventSpy.callCount).toBe(1);
expect(this.eventSpy).toHaveBeenCalledWith(this.model, 'cannot have an empty title');

更新しました

あなたが今得ているエラー、「スパイを期待していましたが、関数を手に入れました」はまさにそのためです。Sinon ライブラリ Spy を使用しており、それを Jasmine Spy を期待する Jasmine 関数に渡しています。

次のいずれかを行う必要があります。

this.eventSpy = jasmine.createSpy();

また

expect(this.eventSpy.calledOnce).toBe(true);
expect(this.eventSpt.calledWith(this.model, 'cannot have an empty title')).toBe(true);

ジャスミンと一緒にシノンを使用した理由は何ですか? 最初の解決策をお勧めします。そうすれば、テストが失敗したときに Jasmine が表示する情報が増えるからです。

于 2012-06-01T16:09:28.120 に答える
1

jasmine に sinon固有のマッチャーを追加するjasmine-sinonというライブラリがあります。

それはあなたが次のようなことをすることを可能にします

expect(mySpy).toHaveBeenCalledOnce();
expect(mySpy).toHaveBeenCalledBefore(myOtherSpy);
expect(mySpy).toHaveBeenCalledWith('arg1', 'arg2', 'arg3');
于 2012-06-02T02:41:49.360 に答える