我有一個應該在每次測驗之間清除的類實體,所以我這樣做:
class Foo {
constructor() {}
public bar() {
return console.log("bar")
}
}
describe('tests on class Foo', () => {
let foo: Foo
beforeEach(() => {
foo = new Foo()
jest.clearAllMocks()
})
const spyOnBar = jest.spyOn(foo, "bar")
test("should call bar", () => {
foo.bar()
expect(spyOnBar).toHaveBeenCalled()
})
})
但spyOnBar一直給我錯誤Cannot spyOn on a primitive value; undefined given。
有一種方法可以監視方法欄而不在每個測驗中宣告間諜?
uj5u.com熱心網友回復:
請參閱描述和測驗塊的執行順序。
讓我們看看執行的順序。
describe('tests on class Foo', () => {
beforeEach(() => {
console.log('beforeEach');
});
console.log('describe');
test('should call bar', () => {
console.log('test');
});
});
日志:
PASS stackoverflow/72035574/foo.test.ts (10.376 s)
tests on class Foo
? should call bar (2 ms)
console.log
describe
at Suite.<anonymous> (stackoverflow/72035574/foo.test.ts:16:11)
console.log
beforeEach
at Object.<anonymous> (stackoverflow/72035574/foo.test.ts:13:13)
console.log
test
at Object.<anonymous> (stackoverflow/72035574/foo.test.ts:20:13)
當您在塊中呼叫jest.spyOn(foo, 'bar')方法時,尚未創建實體。這就是你得到錯誤的原因。describefoo
選項 1.在塊中 創建foo實體describe并在其方法上添加 spy。由于所有測驗用例共享一個foo實體和 spy,我們需要呼叫hookjest.clearAllMocks()來beforeEach清除mock.calls和mock.instances屬性,以便每個測驗用例都使用一個清除 spy 物件。toBeCalledTimes(1)意志奏效。
class Foo {
constructor() {}
public bar() {
return console.log('bar');
}
}
describe('tests on class Foo', () => {
const foo = new Foo();
const spyOnBar = jest.spyOn(foo, 'bar');
beforeEach(() => {
jest.clearAllMocks();
});
test('should call bar', () => {
foo.bar();
expect(spyOnBar).toBeCalledTimes(1);
});
test('should call bar - 2', () => {
foo.bar();
expect(spyOnBar).toBeCalledTimes(1);
});
});
選項 2.在鉤子中 創建foo和監視,beforeEach以便每個測驗用例都使用一個新的。沒有必要使用jest.clearAllMocks().
describe('tests on class Foo', () => {
let spyOnBar: jest.SpyInstance;
let foo: InstanceType<typeof Foo>;
beforeEach(() => {
foo = new Foo();
spyOnBar = jest.spyOn(foo, 'bar');
});
test('should call bar', () => {
foo.bar();
expect(spyOnBar).toBeCalledTimes(1);
});
test('should call bar - 2', () => {
foo.bar();
expect(spyOnBar).toBeCalledTimes(1);
});
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/468143.html
