English 中文(简体)
• 我如何测试具有环境变量的APIC端点与MSW的测试
原标题:How can I test API endpoints with environment variables with MSW

我想测试一个需要环境变数的终点。

rror: ❌试图进入客户的服务器边环境变量。

getHash src/services/api.ts:7:23
  5| const getTimestamp = () => Date.now().toString();
  6| const getHash = (timeStamp: string) =>
  7|   md5(timeStamp + env.MARVEL_API_PRIVATE_KEY + env.MARVEL_API_PUBLIC_KEY);

这是我迄今所做的:

import md5 from  md5 ;

import { env } from  @/env ;

const getTimestamp = () => Date.now().toString();
const getHash = (timeStamp: string) =>
  md5(timeStamp + env.MARVEL_API_PRIVATE_KEY + env.MARVEL_API_PUBLIC_KEY);

const timeStamp = getTimestamp();
const hash = getHash(timeStamp);
const query = `ts=${timeStamp}&apikey=${env.MARVEL_API_PUBLIC_KEY}&hash=${hash}`;

export const getCharacters = async () => {
  const url = `${env.MARVEL_API_URL}/characters?limit=50&${query}`;
  const response = await fetch(url);
  const data = response.json();

  return data;
};

ms手:

import { HttpResponse, http } from  msw ;

export const handlers = [
  http.get( /characters , () => {
    return HttpResponse.json(
      {
        id: 1011334,
        name:  3-D Man ,
      },
      { status: 200 },
    );
  }),
];
问题回答

你没有在你@env dir中张贴内容,而是在我的gues上说,你没有适当装载这些物品。

您通常会拥有一个<代码>.env文档或.env. local,作为您项目根基(而不是在任何特别继承中)。 然后自动装入<代码>。

因此,你很可能需要删除你在你的@env dir(或只是把它作为项目根基的.env档案)。

之后又设立了:

KEY=VALUE
KEY2=VALUE2

那么,你会提到他们:

console.log(process.env.KEY)

Additionally, and it may not be relevant here. But in NextJS to expose an env var publically, you need to prepend NEXT_PUBLIC so if you did want to use MARVEL_API_PUBLIC_KEY client side you would need to make it NEXT_PUBLIC_MARVEL_API_PUBLIC_KEY

NextJS has docs here, 包括贵指南内其他瓦尔参考资料的一些有用的内容。





相关问题
Selenium not working with Firefox 3.x on linux

I am using selenium-server , selenium rc for UI testing in my application . My dev box is Windows with FireFox 3.5 and every thing is running fine and cool. But when i try to run selenium tests on my ...

Best browser for testing under Safari Mobile on Linux?

I have an iPhone web app I m producing on a Linux machine. What s the best browser I can use to most closely mimic the feature-limited version of Safari present on the iPhone? (It s a "slimmed down" ...

Code Coverage Tools & Visual Studio 2008 Pro

Just wondering what people are using for code coverage tools when using MS Visual Studio 2008 Pro. We are using the built-in MS test project and unit testing tool (the one that come pre-installed ...

Is there any error checking web app cralwers out there?

Wondering if there was some sort of crawler we could use to test and re-test everything when changes are made to the web app so we know some new change didn t error out any existing pages. Or maybe a ...

热门标签