javascript - Aynı modüldeki birden fazla yöntemi spyOn (jest) ile dinlemek mümkün mü?
TypeScript'te birden fazla yöntemi spyOn yapmam gerekiyor. Bunu TypeScript'te nasıl başarabilirim?
// classA.ts
export class ClassA {
public methodA() {
this.methodB();
this.methodC();
return "ClassA";
}
public methodB() {}
public methodC() {}
}
// classATest.ts
import {ClassA} from './classA';
it('Sample Test', async () => {
const spyOn1 = jest.spyOn(ClassA, 'methodB');
spyOn1.mockImplementation(() => {return () => {}});
const spyOn2 = jest.spyOn(ClassA, 'methodC');
spyOn2.mockImplementation(() => {return () => {}});
const classA = new ClassA();
expect(classA.methodA()).toEqual('ClassA');
});
Şu hatayı alıyorum - Type '"methodC"' olan argüman, '"methodB" | "prototype"' türündeki parametreye atanamaz.
Bir sınıfta birden fazla yöntemde spyOn kullanamaz mıyız? Bunu başarmanın başka bir yolu var mı?
Cevap #1
ClassA.prototype üzerindeki methodB ve methodC yöntemlerini izlemelisiniz. Bunlar örnek yöntemlerdir, STATİK sınıf yöntemleri değildir.
Örn. ClassA.ts:
export class ClassA {
public methodA() {
this.methodB();
this.methodC();
return 'ClassA';
}
public methodB() {}
public methodC() {}
}
ClassA.test.ts:
import { ClassA } from './classA';
describe('61315546', () => {
it('Sample Test', async () => {
const spyOn1 = jest.spyOn(ClassA.prototype, 'methodB');
spyOn1.mockImplementation(() => {
return () => {};
});
const spyOn2 = jest.spyOn(ClassA.prototype, 'methodC');
spyOn2.mockImplementation(() => {
return () => {};
});
const classA = new ClassA();
expect(classA.methodA()).toEqual('ClassA');
});
});
kapsama raporu ile birim testi sonuçları:
PASS stackoverflow/61315546/ClassA.test.ts (12.1s)
61315546
✓ Sample Test (3ms)
-----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 50 | 100 |
ClassA.ts | 100 | 100 | 50 | 100 |
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 13.974s
