如何解决Angular 与旁观者的玩笑:组件测试中的模拟服务方法输出
我正在使用,
Angular CLI:10.2.3
节点:12.22.1
我正在尝试使用 Jest/spectator 设置我的项目以编写测试。
// MyComponent
// my-component.ts
import {MyService} from '../../services/data/my.service';
export class MyComponent implements OnInit {
recordsNum: number;
public manualUploads: Array<any>;
constructor(
private myService: MyService,) { }
// this.manualUploads is populated with relevant data (another method - test works fine for that)
saveRows() {
let requestPayload = this.myService.formatRequestPayload(this.manualUploads);
this.recordsNum = requestPayload.length;
console.log(requestPayload);
..
..
}
}
我想为“saveRows()”添加测试。我正在尝试如下:
// MyComponent Test
// my-component.spec.ts
import { MyComponent } from './my.component';
import {MyService} from '../../services/data/my.service';
import {
createComponentFactory,spectator,} from "@ngneat/spectator/jest";
import { mock,MockProxy } from 'jest-mock-extended';
describe('MyComponent',() => {
let spectator: spectator<MyComponent>;
let upd: any = // prepare the data (for test).
const createComponent = createComponentFactory({
component: MyComponent,declarations: [ObjectKeysPipe],schemas: [NO_ERRORS_SCHEMA],imports: [HttpClientTestingModule,MatSnackBarModule,RouterTestingModule],providers: [
{ provide: DatePipe}
],mocks: [MyService],detectChanges: false
});
beforeEach(() => spectator = createComponent());
// PASS
it('should create',() => {
expect(spectator.component).toBeTruthy();
});
// Some other method in component. PASS
it('should load Validation Rules',() => {
jest.spyOn(spectator.component,'loadValidationRules');
spectator.component.loadValidationRules();
expect(spectator.component.loadValidationRules).toHaveReturned();
});
// saveRows() test. FAIL
it('should save rows',() => {
spectator.component.manualUploads = [upd];
jest.spyOn(spectator.component,'saveRows');
spectator.component.saveRows();
expect(spectator.component.saveRows).toHaveReturned();
});
}
其他测试通过。 saveRows() 的测试失败如下:
? MyComponent > should save rows
TypeError: Cannot read property 'length' of undefined
191 | let requestPayload = this.myService.formatRequestPayload(this.manualUploads);
> 192 | this.recordsNum = requestPayload.length;
| ^
193 | console.log(requestPayload);
194 |
基本上,一个变量(requestPayload)是根据服务方法调用来声明和分配的。
在测试时,我应该如何模拟这个或我应该如何测试这个方法?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。