如何使用茉莉花.js监视所需的功能



我有这段代码(Node.js(:

文件:实用程序.js

// utils.js
const foo = () => {
// ....
}
const bar = () => {
// ....
}
module.exports = { foo, bar }

文件:我的模块.js

// myModule.js
const {
foo,
bar
} = require('./utils');
const bizz = () => {
let fooResult = foo()
return bar(fooResult)
}
module.exports = { bizz }

文件: myModule.spec.js

// myModule.spec.js
const { bizz } = require('./myModule');
describe('myModule', () => {
it('bizz should return bla bla bla', () => {
let foo = jasmine.createSpy('foo').and.returnValue(true)
let bar = jasmine.createSpy('bar').and.callFake((data) => {
expect(date).toBeTrue();
return 'fake-data'
})
expect(bizz()).toBe('fake-data')
})
})

我正在尝试测试bizzfoobar功能上使用间谍,但它运行不佳。

谁能向我解释如何在这些功能上创建间谍以测试bizz??

是的,这是可能的。 您只需要先要求utilsspyOn,然后要求myModule。以下测试将通过。

const utils = require('./utils');
// myModule.spec.js
describe('myModule', () => {
it('bizz should return bla bla bla', () => {
const fooSpy = spyOn(utils, 'foo').and.returnValue(true);
const barSpy = spyOn(utils, 'bar').and.callFake(data => {
expect(data).toBeTrue();
return 'fake-data';
});
const { bizz } = require('./myModule'); // Import myModule after you added the spyOn
expect(bizz()).toBe('fake-data');
expect(fooSpy).toHaveBeenCalled();
expect(barSpy).toHaveBeenCalled();
});
});

希望对你有帮助

似乎不可能。 https://github.com/mjackson/expect/issues/169

最新更新