我有一個模塊叫map-creation.service.ts
:如何使用Jest在TypeScript中模擬導入的函數?
export const createMap = (asyncJobId: string, resourceUrl: string, s3DestFolder: string) => {
};
這是我的終點使用:
import {createMap} from './services/map-creation.service';
const router = express.Router();
const routePrefix = config.get('server.routePrefix');
router.post(`/${routePrefix}`, validate(validation), (req: express.Request, res: express.Response) => {
createMap(req.body.asyncJobId, req.body.resourceUrl, req.body.s3DestFolder);
res.status(201).json({message: 'Created'});
});
當我試圖嘲弄我在測試這個模塊,並想測試,如果它是請求端點調用時,我仍然得到:Expected mock function to have been called with: ... But it was not called.
jest.mock('../../../src/services/map-creation.service');
import {createMap} from '../../../src/services/map-creation.service';
這是我的測試:
it('should call the map-creation service',() => {
return request(server)
.post(`/${routePrefix}`)
.send({
asyncJobId,
resourceUrl,
s3DestFolder
})
.then(res => {
expect(createMap).toBeCalledWith(asyncJobId, resourceUrl, s3DestFolder);
});
});
如果我嘲笑這樣的方法:
import {createMap} from '../../../src/services/map-creation.service';
createMap = jest.fn();
測試通過,但tslint抱怨:Cannot assign to 'createMap' because it is not a variable
。那麼在TypeScript和Jest中嘲笑這種方法的正確方法是什麼?
我相信你必須調用'jest.mock'給它與導入時相同的參數。 因此,如果從'./services/map-creation.service'使用'import {createMap};' 然後將它嘲笑爲'jest.mock('./services/map- creation.service');',你可以在模塊的相同目錄下找到你的測試(這是常見的做法)。 – jevgenig
另一個選擇是配置TS使用非相對模塊導入[鏈接](https://www.typescriptlang.org/docs/handbook/module-resolution.html) (背後的想法是,笑話實際上並不理解這兩個用於導入和模擬的路徑是相同的) – jevgenig