首页 > 解决方案 > 尝试模拟 const 在 nodejs 中不起作用

问题描述

我一直在尝试在 movie.js 中模拟 fetchFromCache 方法,但到目前为止还不可能。我尝试了很多东西,但我认为编写方式使一切变得更加复杂。我无法更改代码,因为有很多东西是这样写的,我现在正在添加单元测试。我尝试的最后一件事是这样:

jest.mock('../src/movie', () => ({
    fetchFromCache: 'number fake'
  }));


fetchMovieHandler.js

const Movie = require('./movie');

exports.handler = async function (event) {
    let movieId = event.movieId;

    return Movie.getMovieId(movieId);
};


movie.js

    const getMovieId = movieId => 
                                Promise.resolve(fetch(movieId))


    const fetchMovieFromCache = movieId => {
        return fetchFromCache(movieId)

    }

    const fetchFromCache = movieId => new Promise((resolve, reject) => {
           cacheClient.get(movieId, 
        (err, data) => { 
            if(data) {
                return resolve(data);
            } else {
                return resolve(null);
            }});
    });


Testing
const fetchMovieHandler = require("../src/fetchMovieHandler");

describe('Movie Id', () => {
    test("movie id valid", () => {
        return fetchMovieHandler.handler(event("123")).then(value => {
            expect(value).toBe("value returned");
        })
    });
})

const event = (movieId) => {
    return {
        "movieId": movieId
    };
}

得到

Movie.getMovieId is not a function

任何想法?

标签: javascriptnode.jsmocking

解决方案


推荐阅读