angular - TypeError : jasmine. createSpyObj 不是函数

标签 angular jasmine

我需要对不返回 Promise 的组件方法进行单元测试,但在内部调用服务中的方法,因此单元测试执行立即返回到“it”块。这导致我应该查看某些值的对象尚未分配。 Angular documentation suggests that I use a Spy object .这似乎正是我所需要的。不幸的是,即使是最基本的单元测试也不会让我创建 Spy 对象。

下面的代码...

describe('my unit test', () => {

    var myService;

    beforeEach(() => {
        myService = jasmine.createSpyObj('myService', ['myMethodOne', 'myMethodTwo']);
        myService.myMethodOne();
    });

    it("my service test", () => {
        expect(myService.myMethodOne).toBeDefined();
        expect(myService.myMethodOne).toHaveBeenCalled();
    });

});

失败...
>npm test

> iwp-app@0.0.0 test D:\Users\brock\Source
> jest

 FAIL  component.spec.ts
  my unit test
    × my service test (41ms)

  ● my unit test › my service test

    TypeError: jasmine.createSpyObj is not a function

      at component.spec.ts:29:25
      at ZoneDelegate.Object.<anonymous>.ZoneDelegate.invoke (node_modules/zone.js/dist/zone.js:388:26)
      at ProxyZoneSpec.Object.<anonymous>.ProxyZoneSpec.onInvoke (node_modules/zone.js/dist/proxy.js:128:39)
      at ZoneDelegate.Object.<anonymous>.ZoneDelegate.invoke (node_modules/zone.js/dist/zone.js:387:32)
      at Zone.Object.<anonymous>.Zone.run (node_modules/zone.js/dist/zone.js:138:43)
      at Object.testBody.length (node_modules/jest-zone-patch/index.js:50:27)

  ● my unit test › my service test

    TypeError: Cannot read property 'myMethodOne' of undefined

      at create-template.component.spec.ts:34:22
      at ZoneDelegate.Object.<anonymous>.ZoneDelegate.invoke (node_modules/zone.js/dist/zone.js:388:26)
      at ProxyZoneSpec.Object.<anonymous>.ProxyZoneSpec.onInvoke (node_modules/zone.js/dist/proxy.js:128:39)
      at ZoneDelegate.Object.<anonymous>.ZoneDelegate.invoke (node_modules/zone.js/dist/zone.js:387:32)
      at Zone.Object.<anonymous>.Zone.run (node_modules/zone.js/dist/zone.js:138:43)
      at Object.testBody.length (node_modules/jest-zone-patch/index.js:50:27)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        4.36s
Ran all test suites.
npm ERR! Test failed.  See above for more details.

最佳答案

Jest 没有像默认 jasmine 那样名为 createSpyObj() 的函数,请访问此链接 Jest createSpyObj
这是一个自定义的 createSpyObj 函数,或者只是切换到 jasmine

关于angular - TypeError : jasmine. createSpyObj 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52191258/

相关文章:

angular - Jasmine 测试,导致 mat-select 发出 selectionChange 事件?

angular - ngrx 4 测试效果 jasmine-marbles

javascript - 如果提供相等的类,angular2 测试中的 useClass 字段是否有任何区别?

javascript - 模拟 Web 浏览器orientationchange 事件以使用 jasmine 测试绑定(bind)的事件处理函数

html - 可以使用 ionic2/3 更改 ionic 范围方向吗?

提交搜索表单后的 Angular 重定向

javascript - 如何在javascript中做好封装

javascript - Data Bind RouterLink (Angular 2) - 获得插值 ({{}}),其中第 3 列预期有表达式

javascript - Angular Http 发布到 .Net Core

javascript - NPM 递归未满足的对等依赖关系