我需要对不返回 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/