我在用,
角 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)是根据服务方法调用声明和分配的。
在测试时,我应该如何模拟这个或者我应该如何测试这个方法?