使用Chai,您可以创建一个间谍对象,如下所示:
chai.spy.object([ 'push', 'pop' ]);
Run Code Online (Sandbox Code Playgroud)
使用茉莉花,您可以使用:
jasmine.createSpyObj('tape', ['play', 'pause', 'stop', 'rewind']);
Run Code Online (Sandbox Code Playgroud)
什么是Jest等价物?
上下文:我目前正在将(打字稿)Jasmine测试迁移到(typescript)Jest.在这种情况下,迁移指南基本上没用:https://facebook.github.io/jest/docs/migration-guide.html与任何相对较新的技术一样,在这方面的文档中没有任何东西可以轻易找到.
我为jest编写了一个非常快速的createSpyObj函数,以支持旧项目.基本上从Jasmine的实现移植.
export const createSpyObj = (baseName, methodNames): { [key: string]: Mock<any> } => {
let obj: any = {};
for (let i = 0; i < methodNames.length; i++) {
obj[methodNames[i]] = jest.fn();
}
return obj;
};
Run Code Online (Sandbox Code Playgroud)
const video = {
play() {
return true;
},
};
module.exports = video;
Run Code Online (Sandbox Code Playgroud)
而且测试:
const video = require('./video');
test('plays video', () => {
const spy = jest.spyOn(video, 'play');
const isPlaying = video.play();
expect(spy).toHaveBeenCalled();
expect(isPlaying).toBe(true);
spy.mockReset();
spy.mockRestore();
});
Run Code Online (Sandbox Code Playgroud)
在这里找到的文档:https://facebook.github.io/jest/docs/en/jest-object.html#jestspyonobject-methodname
还有jest.fn()
const mockFn = jest.fn();
mockFn();
expect(mockFn).toHaveBeenCalled();
// With a mock implementation:
const returnsTrue = jest.fn(() => true);
console.log(returnsTrue()); // true;
Run Code Online (Sandbox Code Playgroud)
https://facebook.github.io/jest/docs/en/jest-object.html#jestfnimplementation
| 归档时间: |
|
| 查看次数: |
7830 次 |
| 最近记录: |