gpt4 book ai didi

javascript - 使用 React Native 和 Contentful 进行 Jest 测试

转载 作者:行者123 更新时间:2023-11-29 16:02:14 25 4
gpt4 key购买 nike

我正在尝试使用 Jest 测试我的 React Native 应用程序。我正在使用 Contentful 作为 CMS 来保存我的后端信息。我目前正在尝试测试我是否正在初始化正确的客户端。

这是我用来初始化客户端的代码:

var client = contentful.createClient({
space: 'w20789877', // whatever the space id is
accessToken: '883829200101001047474747737' // some accessToken
})

这是我用来测试初始化​​客户端的代码:

describe ('should initialize the correct client', () => {(
it('should initialize the correct client info from contentful', () =>{
expect(client).toEqual('w20789877', '883829200101001047474747737')
});
)};

但是,我收到一条错误消息,指出:

Difference: Comparing two different types of values. Expected undefined but received string.

出于某种原因,我收到了未定义的空间和 accessToken,但我正确地初始化了客户端,因为我稍后可以使用该空间。即使在尝试打印出空间和 accessToken 时,也会打印出未定义的值。

最佳答案

这里有几个问题:

  1. toEqual 匹配器接收单个值参数;你要发送 2参数,因此实际上只使用了第一个参数。
  2. 本例中的client 是一个函数,您正试图将它与字符串进行比较。不管客户端不是字符串这一事实,在您的情况下它也是 undefined,因此出现消息“Expected undefined but received string”。您在这里不是在测试空间或 accessToken,而是在测试客户端。

我不完全确定您要在这里测试什么,但这与 Contentful 没有特别相关。

我假设客户端初始化部分位于您要进行单元测试的代码中的某处(而不是在测试文件中初始化)。我建议进行一项测试,检查执行代码时是否使用预期参数调用了 contentfulcreateClient 函数;无需测试客户端是否已创建 - 这是 Contentful 的责任,以确保它们返回有效的客户端对象。重要的是您传递应用所需的正确“space”和“accessToken”参数。

一般来说,外部服务应该被模拟,你应该只测试你自己的逻辑和与外部服务的交互。

例子

为简单起见,假设初始化客户端的代码如下所示:

//client.js

var contentful = require('contentful')

export default function initializeClient() {
var client = contentful.createClient({
space: 'w20789877', // whatever the space id is
accessToken: '883829200101001047474747737' // some accessToken
});
}

测试可能看起来像这样:

//client.test.js

describe('contentful client', () => {
let contentful;
let initializeClient;

beforeEach(() => {
jest.mock('contentful');

contentful = require('contentful');
initializeClient = require('./client').default;
});

it('should initialize the contentful client with the correct params', async () => {
initializeClient();
expect(contentful.createClient).toHaveBeenCalledWith({
space: 'w20789877',
accessToken: '883829200101001047474747737'
});
});
});

注意:我没有实际运行或测试上面的代码,但这是一般概念。

关于javascript - 使用 React Native 和 Contentful 进行 Jest 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51153981/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com