我需要对不返回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.
答案 0 :(得分:0)
Jest没有像默认的茉莉花一样具有名为createSpyObj()的函数,请访问此链接Jest createSpyObj 这是一个自定义的自定义createSpyObj函数,或者只是切换到茉莉花