[英]In Jest, mock a Node module that's in a user module, in a test block
我有一个名为files.js
的用户模块。 它使用全局的 Node模块,如下所示:
const globby = require('globby');
module.exports = {
/**
* Get the paths for files in the current directory.
*
* @returns {Promise<string[]>} The file paths.
*/
async getFiles() {
return await globby(__dirname);
},
};
我有一个files.test.js
测试文件,如下所示:
const globby = require('globby');
const path = require('path');
const files = require('./files');
describe('files', () => {
test('get files', async () => {
const items = await files.getFiles();
// The files that we expect are the ones in the current directory. Prepend
// the current directory to each filename, so that they are absolute paths.
const expectedFiles = ['files.js', 'files.test.js'];
const expected = expectedFiles.map((file) => path.join(__dirname, file));
expect(items).toEqual(expected);
});
test('get files (mocked)', async () => {
// Try to mock the `globby` module.
jest.mock('globby');
globby.mockResolvedValue(['Test.js']);
// Get the files, but expect the mocked value that we just set.
const items = await files.getFiles();
expect(items).toEqual(['Test.js']);
});
});
第一个测试通过了,但是第二个测试失败了,因为globby
的解析值未能正确模拟。 我已经使用jest.mock
, jest.doMock
等进行了尝试,但是我无法正确模拟globby
的值,因此在getFiles
对globby
的调用中它返回['Test.js']
。
我如何正确模拟globby
的解析值,以便它在单个测试块中从getFiles
返回我想要的?
目前,我只是将测试分为两个文件,一个文件包含需要globby
的测试的模拟,另一个文件包含需要globby
测试的globby
,但是我希望有一个更优雅的解决方案可以做到这一点全部在同一个文件中。
我想到的一种解决方案是:
const path = require('path');
let files = require('./files');
describe('files', () => {
beforeEach(() => {
jest.resetModules();
});
test('get files', async () => {
const items = await files.getFiles();
// The files that we expect are the ones in the current directory. Prepend
// the current directory to each filename, so that they are absolute paths.
const expectedFiles = ['files.js', 'files.test.js'];
const expected = expectedFiles.map((file) => path.join(__dirname, file));
expect(items).toEqual(expected);
});
test('get files (mocked)', async () => {
jest.doMock('globby');
const globby = require('globby');
files = require('./files');
globby.mockResolvedValue(['Test.js']);
// Get the files, but expect the mocked value that we just set.
const items = await files.getFiles();
expect(items).toEqual(['Test.js']);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.