Vitest Mock Factory 从未被调用

huangapple go评论68阅读模式
英文:

Vitest Mock Factory Never Called

问题

这一行 console.log(ssmClient) 看到了吗?它打印的是真实的实现,而不是模拟对象,尽管它应该返回 ssmClientMock(在生产代码中也发生了这种情况 - 它看到的是真实实现,而不是模拟)。我在这里缺少了什么? 🤔

英文:

Here is my code:

import { it, describe, expect, vi, beforeEach } from 'vitest';
const ClientAuthenticator = require('../src/client-authenticator');
const { ssmClient, getParameterCommand } = require('../src/helpers/aws');

const ssmClientMock = vi.fn();
const getParameterCommandMock = vi.fn();

vi.mock('../src/helpers/aws', () => {
    return {
        ssmClient: ssmClientMock,
        getParameterCommand: getParameterCommandMock,
    };
});

describe('ClientAuthenticator.authenticator Tests', () => {
    it('Should set correct client name', async () => {
        // Arrange
        console.log(ssmClient); // This logs real implementation not a mock.
        const clientId = 'clientId';
        const clientSecret = 'clientSecret';
        ... rest of the test ...

See that line that says console.log(ssmClient)? this one prints real implementation not the mock though it should return ssmClientMock (this happens also in the production code - it sees the real implementation not the mock.) What am I missing here? 🤔

答案1

得分: 0

Vitest 原来适用于 ES6 模块。如果你使用 require,它不会产生影响。更多详情请参考这里:https://vitest.dev/api/vi.html#vi-mock

英文:

It turned out that Vitest works with ES6 modules. It has no effect if you're using require. More details are given here: https://vitest.dev/api/vi.html#vi-mock

huangapple
  • 本文由 发表于 2023年6月11日 20:24:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76450464.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定