spyOn
modules
// myModule.ts
export function foo () {
return true
}
// anotherModule.spec.ts
import * as myModule from './myModule'
const spyOnMyModule = jest.spyOn(myModule, 'foo')
spyOnMyModule.mockReturnValue(true)
const table = document.createElement('div');
const mockTableSetScrollTop = jest.fn()
Object.defineProperty(table, 'scrollTop', {
get: () => 500,
set: mockTableSetScrollTop,
});
import * as myModule from '...'
const spyOnMyModule = jest.spyOn(myModule, 'foo')
// Method 1:
expect(
spyOnMyModule.mock.lastCall[0]
).toMatchObject({ ... });
// Method 2:
expect(
spyOnMyModule.mock.call[0][0]
).toMatchObject({ ... });
// Method 3:
expect(spyOnMyModule).toBeCalledWith(
expect.objectContaining({
...
})
);
describe()
之間的執行順序
describe('describe A', () => {
console.log('1')
beforeAll(() => console.log('3'))
})
describe('describe B', () => {
console.log('2')
beforeAll(() => console.log('4'))
})
執行順序:1 → 2 → 3 → 4
在 describe
區塊直接呼叫 jest.spyOn()
,可能會導致後面的 describe B 把前面 describe A 的給覆蓋掉。
it('should scroll to end', async () => {
const mockScrollTo = jest.fn();
window.HTMLElement.prototype.scrollTo = mockScrollTo;
const wrapper = mount(App);
wrapper.vm.scrollToEnd();
expect(mockScrollTo).toBeCalled();
});
jest --coverage
jest --coverage --collectCoverageFrom=<file-path>
jest --watch
jest --watchAll
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up