我在從我擁有的這個模塊模式設定 (MyConnection.js) 中獲得獨特的搜索實作時遇到了麻煩 - 這與我擁有的相似:
// MyConnection.js
const MyConnection = () => {
const search = async (q) => {
//...some functionality
};
return {
search,
};
};
//JEST TESTS
const MyConnection = require('../MyConnection')
// this works - but it sets the search implementation
// for the whole test file I believe
jest.mock('../MyConnection', () => {
return jest.fn(()=>{
search: ()=> ['mocked', 'fn', 'results']
})
})
//the jest tests - I want different
// implementations of search in each test
describe('connection tests', ()=>{
it('test one', ()=>{
//Not sure if its something like this to set 'search' for each test? This doesn't work as is
MyConnection.search.mockImplementation((q)=>{`You searched ${q}`})
})
it('test two', ()=>{
MyConnection.search.mockImplementation((q)={q.length>32? 'a': 'b' }})
})
})
如何為每個測驗獲得該搜索功能的獨特 Jest 模擬實作?
uj5u.com熱心網友回復:
您應該確保模擬MyConnection始終在您的測驗檔案和您要測驗的模塊中回傳相同的連接物件。
MyConnection.js:
const MyConnection = () => {
const search = async (q) => {};
return {
search,
};
};
module.exports = MyConnection;
main.js:
const MyConnection = require('./MyConnection');
async function main(q) {
const conn = MyConnection();
return conn.search(q);
}
module.exports = main;
main.test.js:
const MyConnection = require('./MyConnection');
const main = require('./main');
jest.mock('./MyConnection', () => {
console.log('MyConnection module gets mocked');
const conn = { search: jest.fn() };
return jest.fn(() => conn);
});
const mConn = MyConnection();
describe('connection tests', () => {
it('test one', async () => {
mConn.search.mockImplementation((q) => {
return `You searched ${q}`;
});
const actual = await main('teresa teng');
expect(actual).toBe('You searched teresa teng');
});
it('test two', async () => {
mConn.search.mockImplementation((q) => {
return q.length > 32 ? 'a' : 'b';
});
const actual = await main('_');
expect(actual).toBe('b');
});
});
測驗結果:
PASS examples/70132655/main.test.js (10.454 s)
connection tests
? test one (2 ms)
? test two (1 ms)
console.log
MyConnection module gets mocked
at examples/70132655/main.test.js:5:11
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 10.903 s
你不能像這樣嘲笑它:
jest.mock('./MyConnection', () => {
console.log('MyConnection module gets mocked');
return jest.fn(() => { search: jest.fn() });
});
為什么?因為每次呼叫MyConnection()測驗檔案或要測驗的檔案中的函式。它將回傳一個新的模擬物件( { search: jest.fn() }),被測檔案和測驗用例中的模擬物件是不一樣的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/370992.html
標籤:javascript 单元测试 玩笑
上一篇:編譯Java單元測驗非常慢
